2011-09-01 253 views
1

从下面的代码或ValueMutationEventHandler,为什么我不能future2.get(),等待future2完成,然后得到结果?Java Future.get()不返回

如果我做future2.get(),它会一直等下去。

import java.util.concurrent.BrokenBarrierException; 
    import java.util.concurrent.CyclicBarrier; 
    import java.util.concurrent.ExecutionException; 
    import java.util.concurrent.ExecutorService; 
    import java.util.concurrent.Executors; 
    import java.util.concurrent.Future; 
    import java.util.concurrent.TimeoutException; 

    import junit.framework.Assert; 

    import org.junit.Test; 

    import com.lmax.disruptor.BatchEventProcessor; 
    import com.lmax.disruptor.ClaimStrategy; 
    import com.lmax.disruptor.RingBuffer; 
    import com.lmax.disruptor.WaitStrategy; 

    int numPublisher = 1; 
    int numConsumer = 1; 
    int parties = numPublisher + numConsumer; 
    CyclicBarrier barrier = new CyclicBarrier(parties); 

    RingBuffer<ValueEvent> ringBuffer = new RingBuffer<ValueEvent>(
      ValueEvent.EVENT_FACTORY, 8192, 
      ClaimStrategy.Option.MULTI_THREADED, 
      WaitStrategy.Option.YIELDING 
    ); 

    int iteration = 10; 
    ValuePublisher valuePublisher = new ValuePublisher(
      barrier, ringBuffer, iteration 
    ); 

    ExecutorService execService = Executors.newFixedThreadPool(2); 
    Future future = execService.submit(valuePublisher); 

    ValueMutationEventHandler eventHandler = new ValueMutationEventHandler(Operation.ADDITION); 

    BatchEventProcessor<ValueEvent> eventProcessor = new BatchEventProcessor<ValueEvent>(ringBuffer, 
      ringBuffer.newDependencyBarrier(), 
      eventHandler 
    ); 

    barrier.await(); 
    Future future2 = execService.submit(eventProcessor); 

    ////////////////////////////// 
    // Why do I need sleep here? Why doesn't future2.get works? 
    ///////////////////////////// 
    Thread.sleep(1000); 

    Assert.assertEquals(eventHandler.getValue(), 45L); 

回答

2

您可以使用get(long timeout, TimeUnit unit)以免等待很长时间并超时操作。

使用上面,而不是Thread.sleep(1000);,你不需要Thread.sleep(int)

的Future.get如果不返回......你可能需要检查BatchEventProcessor看到什么在那里发生的。如果它不返回对象Future.get不能返回任何东西。将调试点放入BatchEventProcessor以确保它在所需的预期时间范围内真正返回结果。