test/java/util/concurrent/locks/Lock/FlakyMutex.java

Print this page

        

@@ -29,29 +29,42 @@
  */
 
 import java.util.*;
 import java.util.concurrent.*;
 import java.util.concurrent.locks.*;
+import java.lang.reflect.Field;
+import sun.misc.Unsafe;
 
 /**
  * This uses a variant of the standard Mutex demo, except with a
  * tryAcquire method that randomly throws various Throwable
  * subclasses.
  */
 @SuppressWarnings({"deprecation", "serial"})
 public class FlakyMutex implements Lock {
+    private static final Unsafe UNSAFE;
+    static {
+        try {
+            Field f = Unsafe.class.getDeclaredField("theUnsafe");
+            f.setAccessible(true);
+            UNSAFE = (Unsafe)f.get(null);
+        } catch (NoSuchFieldException | IllegalAccessException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
     static class MyError extends Error {}
     static class MyException extends Exception {}
     static class MyRuntimeException extends RuntimeException {}
 
     static final Random rnd = new Random();
 
     static void maybeThrow() {
         switch (rnd.nextInt(10)) {
         case 0: throw new MyError();
         case 1: throw new MyRuntimeException();
-        case 2: Thread.currentThread().stop(new MyException()); break;
+        case 2: UNSAFE.throwException(new MyException()); break;
         default: /* Do nothing */ break;
         }
     }
 
     static void checkThrowable(Throwable t) {