fixed bug #929: close async service before the main thread finishes (#931)

This commit is contained in:
Zhang WH 2019-09-30 23:32:29 +08:00 committed by Ilkka Seppälä
parent 06fa92af2c
commit 3d62e02891
2 changed files with 18 additions and 0 deletions

View File

@ -94,6 +94,8 @@ public class App {
service.execute(new ArithmeticSumTask(500));
service.execute(new ArithmeticSumTask(2000));
service.execute(new ArithmeticSumTask(1));
service.close();
}
/**

View File

@ -22,6 +22,9 @@
*/
package com.iluwatar.halfsynchalfasync;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
@ -38,6 +41,7 @@ import java.util.concurrent.TimeUnit;
*/
public class AsynchronousService {
private static final Logger LOGGER = LoggerFactory.getLogger(AsynchronousService.class);
/*
* This represents the queuing layer as well as synchronous layer of the pattern. The thread pool
* contains worker threads which execute the tasks in blocking/synchronous manner. Long running
@ -95,4 +99,16 @@ public class AsynchronousService {
}
});
}
/**
* Stops the pool of workers. This is a blocking call to wait for all tasks to be completed.
*/
public void close() {
service.shutdown();
try {
service.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException ie) {
LOGGER.error("Error waiting for executor service shutdown!");
}
}
}