Java ExecutorService invokeAll () прерывая - PullRequest
7 голосов
/ 02 ноября 2011

У меня есть фиксированный пул потоков ExecutorService шириной 10 и список 100 Callable, каждый из которых ожидает по 20 секунд и записывает свои прерывания.

Я звоню invokeAll по этому списку в отдельном потоке и почти немедленно прерываю этот поток. ExecutorService выполнение прерывается, как и ожидалось, но фактическое количество прерываний, записанных Callable с, намного больше, чем ожидалось 10 - около 20-40. Почему так, если ExecutorService может одновременно выполнять не более 10 потоков?

Полный источник: (Вам может потребоваться запустить его несколько раз из-за параллелизма)

@Test
public void interrupt3() throws Exception{
    int callableNum = 100;
    int executorThreadNum = 10;
    final AtomicInteger interruptCounter = new AtomicInteger(0);
    final ExecutorService executorService = Executors.newFixedThreadPool(executorThreadNum);
    final List <Callable <Object>> executeds = new ArrayList <Callable <Object>>();
    for (int i = 0; i < callableNum; ++i) {
        executeds.add(new Waiter(interruptCounter));
    }
    Thread watcher = new Thread(new Runnable() {

        @Override
        public void run(){
            try {
                executorService.invokeAll(executeds);
            } catch(InterruptedException ex) {
                // NOOP
            }
        }
    });
    watcher.start();
    Thread.sleep(200);
    watcher.interrupt();
    Thread.sleep(200);
    assertEquals(10, interruptCounter.get());
}

// This class just waits for 20 seconds, recording it's interrupts
private class Waiter implements Callable <Object> {
    private AtomicInteger    interruptCounter;

    public Waiter(AtomicInteger interruptCounter){
        this.interruptCounter = interruptCounter;
    }

    @Override
    public Object call() throws Exception{
        try {
            Thread.sleep(20000);
        } catch(InterruptedException ex) {
            interruptCounter.getAndIncrement();
        }
        return null;
    }
}

Использование WinXP 32-bit, Oracle JRE 1.6.0_27 и JUnit4

Ответы [ 3 ]

4 голосов
/ 03 ноября 2011

Я не согласен с гипотезой, что вы должны получать только 10 прерываний.

Assume the CPU has 1 core.
1. Main thread starts Watcher and sleeps
2. Watcher starts and adds 100 Waiters then blocks
3. Waiter 1-10 start and sleep in sequence
4. Main wakes and interrupts Watcher then sleeps
5. Watcher cancels Waiter 1-5 then is yielded by the OS   (now we have 5 interrupts)
6. Waiter 11-13 start and sleep
7. Watcher cancels Waiter 6-20 then is yielded by the OS   (now we have 13 interrupts)
8. Waiter 14-20 are "started" resulting in a no-op
9. Waiter 21-24 start and sleep
....

По сути, я утверждаю, что нет никакой гарантии, что потоку Watcher будет разрешено отменить все 100 экземпляров RunnableFuture "Waiter", прежде чем он должен будет выдавать временной интервал и позволить рабочим потокам ExecutorService запускать больше задач Waiter.

Обновление: Отображение кода от AbstractExecutorService

public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
    throws InterruptedException {
    if (tasks == null)
        throw new NullPointerException();
    List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
    boolean done = false;
    try {
        for (Callable<T> t : tasks) {
            RunnableFuture<T> f = newTaskFor(t);
            futures.add(f);
            execute(f);
        }
        for (Future<T> f : futures) {
            if (!f.isDone()) {
                try {
                    f.get(); //If interrupted, this is where the InterruptedException will be thrown from
                } catch (CancellationException ignore) {
                } catch (ExecutionException ignore) {
                }
            }
        }
        done = true;
        return futures;
    } finally {
        if (!done)
            for (Future<T> f : futures)
                f.cancel(true); //Specifying "true" is what allows an interrupt to be sent to the ExecutorService's worker threads
    }
}

Блок finally, который содержит f.cancel(true), - это когда прерывание распространяется на задачу, которая в данный момент выполняется. Как вы можете видеть, это узкий цикл, но нет никакой гарантии, что поток, выполняющий цикл, сможет перебирать все экземпляры Future в одном временном интервале.

1 голос
/ 15 августа 2014

Если вы хотите добиться того же поведения

    ArrayList<Runnable> runnables = new ArrayList<Runnable>();
    executorService.getQueue().drainTo(runnables);

Добавление этого блока перед прерыванием пула потоков.

Это опустошит всю очередь ожидания в новый список.

Так что он будет прерывать только запущенные потоки.

0 голосов
/ 25 марта 2013
PowerMock.mockStatic ( Executors.class );
EasyMock.expect ( Executors.newFixedThreadPool ( 9 ) ).andReturn ( executorService );

Future<MyObject> callableMock = (Future<MyObject>) 
EasyMock.createMock ( Future.class );
EasyMock.expect ( callableMock.get ( EasyMock.anyLong (), EasyMock.isA ( TimeUnit.class ) ) ).andReturn ( ccs ).anyTimes ();

List<Future<MyObject>> futures = new ArrayList<Future<MyObject>> ();
futures.add ( callableMock );
EasyMock.expect ( executorService.invokeAll ( EasyMock.isA ( List.class ) ) ).andReturn ( futures ).anyTimes ();

executorService.shutdown ();
EasyMock.expectLastCall ().anyTimes ();

EasyMock.expect ( mock.getMethodCall ( ) ).andReturn ( result ).anyTimes ();

PowerMock.replayAll ();
EasyMock.replay ( callableMock, executorService, mock );

Assert.assertEquals ( " ", answer.get ( 0 ) );
PowerMock.verifyAll ();
...