ExecutorService workStealingPool and undo method

Can you think of any reason why this code does not work and always displays "finished", but the second example works without problems. I am using the latest JDK (8u45).

public static class MyClass implements Runnable {

        @Override
        public void run () {
            try {
                Thread.sleep (2000);
            } catch (InterruptedException ex) {
                System.out.println ("Interrupted");
                return
            }
            System.out.println ("Finished");
        }

        public static void main (String [] args) {
             // spot the difference ->
             ExecutorService executorService = Executors.newWorkStealingPool (4);
             Future future = executorService.submit (new MyClass ());
             Thread.sleep (100);
             future.cancel (true);
        }
    }

And the following example works flawlessly:

public static class MyClass implements Runnable {

        @Override
        public void run () {
            try {
                Thread.sleep (2000);
            } catch (InterruptedException ex) {
                System.out.println ("Interrupted");
                return
            }
            System.out.println ("Finished");
        }

        public static void main (String [] args) {
             ExecutorService executorService = Executors.newSingleThreadExecutor ();
             Future future = executorService.submit (new MyClass ());
             Thread.sleep (100);
             future.cancel (true);
        }
    }

EDIT: Added reverse and updated sleep times and another example.

+4
2

, . , "--" ForkJoinPool, ForkJoinTask (true), .

. javadoc (http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinTask.html):

   mayInterruptIfRunning - this value has no effect in the default implementation 
   because interrupts are not used to control cancellation.
+4

Thread Java. ( Java 1.0 , , , , .)

, Runnable, , run. run catch-block, ; catch. , run.

+2

Source: https://habr.com/ru/post/1584967/


All Articles