2016-02-11 20 views
5

Ho un ThreadPoolExecutor e invio un'attività a esso.Attività futura respinta da ThreadPoolExecutor

private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1)); 

Questo codice sostiene la Runnable al ThreadPoolExecutor.

protected void waitAndSweep(final String symbol) { 

    runnable = new Runnable() { 
     public void run() { /* irrelevant code */ } 
    }; 

    try { 
     Future<?> self = threadPoolExecutor.submit(runnable); 
     futures.add(self); 
    } catch (RejectedExecutionException re) { 
     /* this exception will be thrown when wait and sweep is called more than twice. 
     * threadPoolExecutor can have one running task and one waiting task. 
     */ 
    } catch (Exception e) { 
     logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol, "Exception caught...", e); 
    } 
    } 

Il seguente codice arresta l'attività.

protected synchronized void stop(StrategyEntry entry) throws Exception { 
    for (Object future : futures) { 
     ((Future<?>) future).cancel(true); 
    } 
    futures.clear(); 

    threadPoolExecutor.shutdown(); 
} 

Il problema qui è: Quando provo a fermare l'operazione, io sono sempre seguente eccezione:

Task [email protected] respinto da java.util.concurrent. ThreadPoolExecutor @ 216393fb [Terminato, dimensioni del pool = 0, thread attivi = 0, in coda tasks = 0, attività completate = 1]

+0

Chiama 'shutdown()' su questo esecutore da qualche parte? – RAnders00

+0

metodo sì in stop – MMPgm

+0

Si sta creando una coda di supporto con capacità 1 - ci sono già altre attività in là? –

risposta

5

il problema è che si shutdown() l'excutor nel metodo di arresto. Se si desidera solo attendere il completamento dell'attività, utilizzare Future.get(). Quando un esecutore viene spento, le attività non possono più essere inviate ad esso.

shutdown() deve essere utilizzato solo quando si desidera effettivamente terminare l'applicazione.

+0

Quando l'executor è spento, non voglio che venga inviata alcuna nuova attività – MMPgm

+0

@MMPgm Dalla tua domanda, non è del tutto chiaro cosa ti aspetti da 'stop() 'metodo per farlo davvero. Forse puoi chiarirlo? – RAnders00

+0

Il metodo di arresto dovrebbe terminare tutte le attività in attesa e non dovrebbe accettare altre attività. Volevo solo sapere qual è il caso possibile per l'eccezione che si verifichi. – MMPgm