Java Code Examples for java.util.concurrent.FutureTask#isDone()

The following examples show how to use java.util.concurrent.FutureTask#isDone() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NonblockingScheduledExecutor.java    From mldht with Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected void afterExecute(Runnable r, Throwable t) {
	super.afterExecute(r, t);
	
	if(exceptionHandler != null && r instanceof FutureTask<?>) {
		FutureTask<?> ft = (FutureTask<?>) r;
		if(ft.isDone() && !ft.isCancelled()) {
			try {
				ft.get();
			} catch (InterruptedException | ExecutionException e) {
				exceptionHandler.uncaughtException(null, e.getCause());
			}
		}
		
	}
}
 
Example 2
Source File: NetconfSessionMinaImplTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Test
public void test2SessionAccess() throws InterruptedException {
    NCCopyConfigCallable testCopySession1 = new NCCopyConfigCallable(session1, RUNNING, "candidate");
    NCCopyConfigCallable testCopySession2 = new NCCopyConfigCallable(session2, RUNNING, "candidate");

    FutureTask<Boolean> futureCopySession1 = new FutureTask<>(testCopySession1);
    FutureTask<Boolean> futureCopySession2 = new FutureTask<>(testCopySession2);

    ExecutorService executor = Executors.newFixedThreadPool(2);
    log.info("Starting concurrent execution of copy-config through 2 different sessions");
    executor.execute(futureCopySession1);
    executor.execute(futureCopySession2);

    int count = 0;
    while (count < 10) {
        if (futureCopySession1.isDone() && futureCopySession2.isDone()) {
            executor.shutdown();
            log.info("Finished concurrent 2 session execution");
            return;
        }
        Thread.sleep(100L);
        count++;
    }
    fail("NETCONF test failed to complete.");
}
 
Example 3
Source File: NetconfSessionMinaImplTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Test
public void testConcurrentSameSessionAccessWithChunkedFraming() throws InterruptedException {
    NCCopyConfigCallable testCopyConfig1 = new NCCopyConfigCallable(session3, RUNNING, "candidate");
    NCCopyConfigCallable testCopyConfig2 = new NCCopyConfigCallable(session3, RUNNING, "startup");

    FutureTask<Boolean> futureCopyConfig1 = new FutureTask<>(testCopyConfig1);
    FutureTask<Boolean> futureCopyConfig2 = new FutureTask<>(testCopyConfig2);

    ExecutorService executor = Executors.newFixedThreadPool(2);
    log.info("Starting concurrent execution of copy-config through same session");
    executor.execute(futureCopyConfig1);
    executor.execute(futureCopyConfig2);

    int count = 0;
    while (count < 10) {
        if (futureCopyConfig1.isDone() && futureCopyConfig2.isDone()) {
            executor.shutdown();
            log.info("Finished concurrent same session execution");
            return;
        }
        Thread.sleep(100L);
        count++;
    }
    fail("NETCONF test failed to complete.");
}
 
Example 4
Source File: NetconfSessionMinaImplTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Test
public void testConcurrentSameSessionAccess() throws InterruptedException {
    NCCopyConfigCallable testCopyConfig1 = new NCCopyConfigCallable(session1, RUNNING, "candidate");
    NCCopyConfigCallable testCopyConfig2 = new NCCopyConfigCallable(session1, RUNNING, "startup");

    FutureTask<Boolean> futureCopyConfig1 = new FutureTask<>(testCopyConfig1);
    FutureTask<Boolean> futureCopyConfig2 = new FutureTask<>(testCopyConfig2);

    ExecutorService executor = Executors.newFixedThreadPool(2);
    log.info("Starting concurrent execution of copy-config through same session");
    executor.execute(futureCopyConfig1);
    executor.execute(futureCopyConfig2);

    int count = 0;
    while (count < 10) {
        if (futureCopyConfig1.isDone() && futureCopyConfig2.isDone()) {
            executor.shutdown();
            log.info("Finished concurrent same session execution");
            return;
        }
        Thread.sleep(100L);
        count++;
    }
    fail("NETCONF test failed to complete.");
}
 
Example 5
Source File: MockKafkaProducer.java    From samza with Apache License 2.0 6 votes vote down vote up
public void run() {
  FutureTask[] callbackArray = new FutureTask[callbacksList.size()];
  AtomicReferenceArray<FutureTask> bufferList =
      new AtomicReferenceArray<FutureTask>(callbacksList.toArray(callbackArray));
  ExecutorService executor = Executors.newFixedThreadPool(10);
  try {
    for (int i = 0; i < bufferList.length(); i++) {
      Thread.sleep(sleepTime);
      FutureTask f = bufferList.get(i);
      if (!f.isDone()) {
        executor.submit(f).get();
      }
    }
  } catch (InterruptedException e) {
    e.printStackTrace();
  } catch (ExecutionException ee) {
    ee.printStackTrace();
  } finally {
    executor.shutdownNow();
  }
}
 
Example 6
Source File: LoggingScheduledThreadPoolExecutor.java    From mldht with Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected void afterExecute(Runnable r, Throwable t) {
	super.afterExecute(r, t);
	
	if(r instanceof FutureTask<?>) {
		FutureTask<?> ft = (FutureTask<?>) r;
		if(ft.isDone() && !ft.isCancelled()) {
			try {
				ft.get();
			} catch (InterruptedException | ExecutionException e) {
				exceptionHandler.accept(e.getCause());
			}
		}
		
		if(t != null)
			exceptionHandler.accept(t);
		
	}
}
 
Example 7
Source File: LoggingScheduledThreadPoolExecutor.java    From bt with Apache License 2.0 6 votes vote down vote up
@Override
protected void afterExecute(Runnable r, Throwable t) {
	super.afterExecute(r, t);
	
	if(r instanceof FutureTask<?>) {
		FutureTask<?> ft = (FutureTask<?>) r;
		if(ft.isDone() && !ft.isCancelled()) {
			try {
				ft.get();
			} catch (InterruptedException | ExecutionException e) {
				exceptionHandler.accept(e.getCause());
			}
		}
		
		if(t != null)
			exceptionHandler.accept(t);
		
	}
}
 
Example 8
Source File: NonblockingScheduledExecutor.java    From bt with Apache License 2.0 6 votes vote down vote up
@Override
protected void afterExecute(Runnable r, Throwable t) {
	super.afterExecute(r, t);
	
	if(exceptionHandler != null && r instanceof FutureTask<?>) {
		FutureTask<?> ft = (FutureTask<?>) r;
		if(ft.isDone() && !ft.isCancelled()) {
			try {
				ft.get();
			} catch (InterruptedException | ExecutionException e) {
				exceptionHandler.uncaughtException(null, e.getCause());
			}
		}
		
	}
}
 
Example 9
Source File: NetconfSessionMinaImplTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Test
public void test2SessionAccessWithChunkedFraming() throws InterruptedException {
    NCCopyConfigCallable testCopySession1 = new NCCopyConfigCallable(session3, RUNNING, "candidate");
    NCCopyConfigCallable testCopySession2 = new NCCopyConfigCallable(session4, RUNNING, "candidate");

    FutureTask<Boolean> futureCopySession1 = new FutureTask<>(testCopySession1);
    FutureTask<Boolean> futureCopySession2 = new FutureTask<>(testCopySession2);

    ExecutorService executor = Executors.newFixedThreadPool(2);
    log.info("Starting concurrent execution of copy-config through 2 different sessions");
    executor.execute(futureCopySession1);
    executor.execute(futureCopySession2);

    int count = 0;
    while (count < 10) {
        if (futureCopySession1.isDone() && futureCopySession2.isDone()) {
            executor.shutdown();
            log.info("Finished concurrent 2 session execution");
            return;
        }
        Thread.sleep(100L);
        count++;
    }
    fail("NETCONF test failed to complete.");
}
 
Example 10
Source File: TestMiniCoronaRunJob.java    From RDFS with Apache License 2.0 5 votes vote down vote up
private void checkTaskNotDone(FutureTask<Boolean> task, int seconds)
    throws Exception {
  for (int i = 0; i < seconds; ++i) {
    if (task.isDone()) {
      // Job should not finish because of the memory limit
      Assert.fail();
    }
    Thread.sleep(1L);
  }
}
 
Example 11
Source File: DependencyFinder.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private Set<Location> waitForTasksCompleted() {
    try {
        Set<Location> targets = new HashSet<>();
        FutureTask<Set<Location>> task;
        while ((task = tasks.poll()) != null) {
            // wait for completion
            if (!task.isDone())
                targets.addAll(task.get());
        }
        return targets;
    } catch (InterruptedException|ExecutionException e) {
        throw new Error(e);
    }
}
 
Example 12
Source File: AThreadPool.java    From ans-android-sdk with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 高优先级同步执行:主要时get类对外操作接口
 *
 * @param callable
 * @return
 */
public static Object syncHighPriorityExecutor(Callable callable) {
    Object object = null;
    FutureTask<Object> futureTask = new FutureTask<Object>(callable);
    highService.execute(futureTask);

    while (!futureTask.isDone() && !futureTask.isCancelled()) {
        try {
            object = futureTask.get();
        } catch (Throwable ignore) {
            ExceptionUtil.exceptionThrow(ignore);
        }
    }
    return object;
}
 
Example 13
Source File: FutureCook.java    From LearningOfThinkInJava with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException, ExecutionException {
    long startTime = System.currentTimeMillis();
    // 第一步 网购厨具
    Callable<Chuju> onlineShopping = new Callable<Chuju>() {

        @Override
        public Chuju call() throws Exception {
            System.out.println("第一步:下单");
            System.out.println("第一步:等待送货");
            Thread.sleep(5000);  // 模拟送货时间
            System.out.println("第一步:快递送到");
            return new Chuju();
        }
        
    };
    FutureTask<Chuju> task = new FutureTask<Chuju>(onlineShopping);
    new Thread(task).start();
    // 第二步 去超市购买食材
    Thread.sleep(2000);  // 模拟购买食材时间
    Shicai shicai = new Shicai();
    System.out.println("第二步:食材到位");
    // 第三步 用厨具烹饪食材
    if (!task.isDone()) {  // 联系快递员,询问是否到货
        System.out.println("第三步:厨具还没到,心情好就等着(心情不好就调用cancel方法取消订单)");
    }
    Chuju chuju = task.get();
    System.out.println("第三步:厨具到位,开始展现厨艺");
    cook(chuju, shicai);
    
    System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");
}
 
Example 14
Source File: ThreadPoolExecutorExtractor.java    From android-test with Apache License 2.0 5 votes vote down vote up
private <T> FutureTask<T> runOnMainThread(final FutureTask<T> futureToRun) {
  if (Looper.myLooper() != Looper.getMainLooper()) {
    final CountDownLatch latch = new CountDownLatch(1);
    mainHandler.post(
        new Runnable() {
          @Override
          public void run() {
            try {
              futureToRun.run();
            } finally {
              latch.countDown();
            }
          }
        });
    try {
      latch.await();
    } catch (InterruptedException ie) {
      if (!futureToRun.isDone()) {
        throw new RuntimeException("Interrupted while waiting for task to complete.", ie);
      }
    }
  } else {
    futureToRun.run();
  }

  return futureToRun;
}
 
Example 15
Source File: FlowEngine.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Hook method called by the thread that executed the given runnable after execution of the runnable completed. Logs the fact of completion and any errors that might have occurred.
 *
 * @param runnable runnable
 * @param throwable throwable
 */
@Override
protected void afterExecute(final Runnable runnable, final Throwable throwable) {
    super.afterExecute(runnable, throwable);
    if (runnable instanceof FutureTask<?>) {
        final FutureTask<?> task = (FutureTask<?>) runnable;
        try {
            if (task.isDone()) {
                if (task.isCancelled()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("A flow controller execution task '{}' has been cancelled.", runnable);
                    }
                } else {
                    task.get(); //to raise any exceptions that might have occurred.
                    logger.debug("A Flow Controller execution task '{}' has completed.", runnable);
                }
            }
        } catch (final CancellationException ce) {
            if (logger.isDebugEnabled()) {
                logger.debug("A flow controller execution task '{}' has been cancelled.", runnable);
            }
        } catch (final InterruptedException ie) {
            if (logger.isDebugEnabled()) {
                logger.debug("A flow controller execution task has been interrupted.", ie);
            }
        } catch (final ExecutionException ee) {
            logger.error("A flow controller task execution stopped abnormally", ee);
        }
    } else {
        logger.debug("A flow controller execution task '{}' has finished.", runnable);
    }
}
 
Example 16
Source File: AbstractBusClientServerTestBase.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected boolean runClient(Runnable clientImpl, long timeOut, TimeUnit timeUnit)
    throws InterruptedException {
    FutureTask<?> client = new FutureTask<>(clientImpl, null);
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 10000L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    tpe.execute(client);
    tpe.shutdown();
    tpe.awaitTermination(timeOut, timeUnit);
    return client.isDone();
}
 
Example 17
Source File: FlowEngine.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Hook method called by the thread that executed the given runnable after execution of the runnable completed. Logs the fact of completion and any errors that might have occurred.
 *
 * @param runnable runnable
 * @param throwable throwable
 */
@Override
protected void afterExecute(final Runnable runnable, final Throwable throwable) {
    super.afterExecute(runnable, throwable);
    if (runnable instanceof FutureTask<?>) {
        final FutureTask<?> task = (FutureTask<?>) runnable;
        try {
            if (task.isDone()) {
                if (task.isCancelled()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("A flow controller execution task '{}' has been cancelled.", runnable);
                    }
                } else {
                    task.get(); //to raise any exceptions that might have occurred.
                    logger.debug("A Flow Controller execution task '{}' has completed.", runnable);
                }
            }
        } catch (final CancellationException ce) {
            if (logger.isDebugEnabled()) {
                logger.debug("A flow controller execution task '{}' has been cancelled.", runnable);
            }
        } catch (final InterruptedException ie) {
            if (logger.isDebugEnabled()) {
                logger.debug("A flow controller execution task has been interrupted.", ie);
            }
        } catch (final ExecutionException ee) {
            logger.error("A flow controller task execution stopped abnormally", ee);
        }
    } else {
        logger.debug("A flow controller execution task '{}' has finished.", runnable);
    }
}
 
Example 18
Source File: FutureExecution.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@Override
public Future<V> apply(InvocationContext<Future<V>> ctx) {
    FutureTask<Future<V>> task = new NamedFutureTask<>("FutureExecution", () -> delegate.apply(ctx));
    executor.execute(task);
    return new Future<V>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            ctx.fireEvent(CancellationEvent.INSTANCE);
            return task.cancel(mayInterruptIfRunning);
        }

        @Override
        public boolean isCancelled() {
            return task.isCancelled();
        }

        @Override
        public boolean isDone() {
            return task.isDone();
        }

        @Override
        public V get() throws InterruptedException, ExecutionException {
            return task.get().get();
        }

        @Override
        public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            // at worst, the timeout here could possibly be 2x the requested value
            return task.get(timeout, unit).get(timeout, unit);
        }
    };
}
 
Example 19
Source File: FutureTaskDemo.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws ExecutionException, InterruptedException {
    FutureTask<String> futureTask = new FutureTask<String>(new MyCallable());
    Thread thread = new Thread(futureTask);
    thread.start();
    if (!futureTask.isDone()){
        System.out.println("task is alive");
    }
    System.out.println(futureTask.get());
    System.out.println("task is dead");
}
 
Example 20
Source File: GangliaPlugIn.java    From database with GNU General Public License v2.0 3 votes vote down vote up
@Override
public boolean isRunning() {

    final FutureTask<Void> ft = gangliaFuture.get();

    if (ft == null || ft.isDone())
        return false;

    return true;
    
}