下面列出了java.util.concurrent.FutureTask#isDone ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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.");
}
@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());
}
}
}
}
@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);
}
}
@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());
}
}
}
}
@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);
}
}
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();
}
}
@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.");
}
@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.");
}
@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.");
}
/**
* 高优先级同步执行:主要时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;
}
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");
}
@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);
}
};
}
/**
* 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);
}
}
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");
}
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);
}
}
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);
}
}
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;
}
/**
* 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);
}
}
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();
}
@Override
public boolean isRunning() {
final FutureTask<Void> ft = gangliaFuture.get();
if (ft == null || ft.isDone())
return false;
return true;
}