本文整理了Java中java.util.concurrent.ExecutorService.shutdownNow()
方法的一些代码示例,展示了ExecutorService.shutdownNow()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ExecutorService.shutdownNow()
方法的具体详情如下:
包路径:java.util.concurrent.ExecutorService
类名称:ExecutorService
方法名:shutdownNow
[英]Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
This method does not wait for actively executing tasks to terminate. Use #awaitTermination to do that.
There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread#interrupt, so any task that fails to respond to interrupts may never terminate.
[中]尝试停止所有正在执行的任务,停止正在等待的任务的处理,并返回正在等待执行的任务的列表。
此方法不会等待主动执行的任务终止。用#等待终止来完成。
除了尽最大努力尝试停止处理积极执行的任务之外,没有其他保证。例如,典型的实现将通过线程中断取消,因此任何未能响应中断的任务可能永远不会终止。
代码示例来源:origin: iluwatar/java-design-patterns
/**
* Stops logging clients. This is a blocking call.
*/
public void stop() {
service.shutdown();
if (!service.isTerminated()) {
service.shutdownNow();
try {
service.awaitTermination(1000, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOGGER.error("exception awaiting termination", e);
}
}
LOGGER.info("Logging clients stopped");
}
代码示例来源:origin: iluwatar/java-design-patterns
/**
* Stops the reactor and related resources such as dispatcher.
*
* @throws InterruptedException
* if interrupted while stopping the reactor.
* @throws IOException
* if any I/O error occurs.
*/
public void stop() throws InterruptedException, IOException {
reactorMain.shutdownNow();
selector.wakeup();
reactorMain.awaitTermination(4, TimeUnit.SECONDS);
selector.close();
LOGGER.info("Reactor stopped");
}
代码示例来源:origin: azkaban/azkaban
public void shutdown() {
this.executorService.shutdown();
this.executorService.shutdownNow();
}
}
代码示例来源:origin: apache/hbase
private void setConfigParallel(FileSystem outputFs, List<Path> traversedPath,
BiConsumer<FileSystem, Path> task, Configuration conf) throws IOException {
ExecutorService pool = Executors
.newFixedThreadPool(conf.getInt(CONF_COPY_MANIFEST_THREADS, DEFAULT_COPY_MANIFEST_THREADS));
List<Future<Void>> futures = new ArrayList<>();
for (Path dstPath : traversedPath) {
Future<Void> future = (Future<Void>) pool.submit(() -> task.accept(outputFs, dstPath));
futures.add(future);
}
try {
for (Future<Void> future : futures) {
future.get();
}
} catch (InterruptedException | ExecutionException e) {
throw new IOException(e);
} finally {
pool.shutdownNow();
}
}
代码示例来源:origin: SonarSource/sonarqube
@Override
public void run() {
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future future = executor.submit(monitored::stop);
future.get(terminationTimeoutMs, TimeUnit.MILLISECONDS);
} catch (Exception e) {
LoggerFactory.getLogger(getClass()).error("Can not stop in {}ms", terminationTimeoutMs, e);
}
executor.shutdownNow();
commands.endWatch();
}
}
代码示例来源:origin: google/j2objc
public void run() {
ExecutorService service = Executors.newSingleThreadExecutor();
Callable<Object> callable = new Callable<Object>() {
public Object call() throws Exception {
runTestMethod();
return null;
}
};
Future<Object> result = service.submit(callable);
service.shutdown();
try {
boolean terminated = service.awaitTermination(timeout,
TimeUnit.MILLISECONDS);
if (!terminated) {
service.shutdownNow();
}
result.get(0, TimeUnit.MILLISECONDS); // throws the exception if one occurred during the invocation
} catch (TimeoutException e) {
addFailure(new Exception(String.format("test timed out after %d milliseconds", timeout)));
} catch (Exception e) {
addFailure(e);
}
}
});
代码示例来源:origin: apache/hive
@Test
public void testGetInputSummaryPoolAndFailure() throws ExecutionException, InterruptedException, IOException {
ExecutorService pool = mock(ExecutorService.class);
when(pool.submit(any(Runnable.class))).thenReturn(mock(Future.class));
Set<Path> pathNeedProcess = new HashSet<>();
pathNeedProcess.add(new Path("dummy-path1"));
pathNeedProcess.add(new Path("dummy-path2"));
pathNeedProcess.add(new Path("dummy-path3"));
SessionState.start(new HiveConf());
JobConf jobConf = new JobConf();
Context context = new Context(jobConf);
Utilities.getInputSummaryWithPool(context, pathNeedProcess, mock(MapWork.class), new long[3], pool);
verify(pool, times(3)).submit(any(Runnable.class));
verify(pool).shutdown();
verify(pool).shutdownNow();
}
代码示例来源:origin: google/guava
ExecutorService executor = newSingleThreadExecutor();
Future<V> waiter =
executor.submit(
new Callable<V>() {
@Override
throw failureWithCause(e, "Unexpected exception");
} finally {
executor.shutdownNow();
代码示例来源:origin: apache/hbase
public static List<Path> copyFilesParallel(FileSystem srcFS, Path src, FileSystem dstFS, Path dst,
Configuration conf, int threads) throws IOException {
ExecutorService pool = Executors.newFixedThreadPool(threads);
List<Future<Void>> futures = new ArrayList<>();
List<Path> traversedPaths;
try {
traversedPaths = copyFiles(srcFS, src, dstFS, dst, conf, pool, futures);
for (Future<Void> future : futures) {
future.get();
}
} catch (ExecutionException | InterruptedException | IOException e) {
throw new IOException("copy snapshot reference files failed", e);
} finally {
pool.shutdownNow();
}
return traversedPaths;
}
代码示例来源:origin: reactive-streams/reactive-streams-jvm
@Test
public void required_spec312_cancelMustMakeThePublisherToEventuallyStopSignaling_shouldFailBy_havingEmitedMoreThanRequested() throws Throwable {
final ExecutorService pool = Executors.newFixedThreadPool(2);
try {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
demandIgnoringAsynchronousPublisherVerification(pool).required_spec312_cancelMustMakeThePublisherToEventuallyStopSignaling();
}
}, /*Publisher signalled [...] */ ", which is more than the signalled demand: ");
} finally {
pool.shutdownNow();
pool.awaitTermination(1, TimeUnit.SECONDS);
}
}
代码示例来源:origin: FudanNLP/fnlp
public void reset() {
pool.shutdownNow();
pool=Executors.newFixedThreadPool(numThread);
f= new ArrayList<Future>();
}
代码示例来源:origin: reactor/reactor-core
@Test
public void multiThreadedProducer() {
UnicastProcessor<Integer> processor = UnicastProcessor.create();
FluxSink<Integer> sink = processor.sink();
int nThreads = 5;
int countPerThread = 10000;
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
for (int i = 0; i < 5; i++) {
Runnable generator = () -> {
for (int j = 0; j < countPerThread; j++) {
sink.next(j);
}
};
executor.submit(generator);
}
StepVerifier.create(processor)
.expectNextCount(nThreads * countPerThread)
.thenCancel()
.verify();
executor.shutdownNow();
}
代码示例来源:origin: stackoverflow.com
public static void main(String args[]) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(new Runnable() {
@Override
public void run() {
while (true) {
if (Thread.currentThread().isInterrupted()) break;
}
}
});
executor.shutdownNow();
if (!executor.awaitTermination(100, TimeUnit.MICROSECONDS)) {
System.out.println("Still waiting...");
System.exit(0);
}
System.out.println("Exiting normally...");
}
代码示例来源:origin: Netflix/eureka
private void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown();
try {
if (!pool.awaitTermination(3, TimeUnit.SECONDS)) {
pool.shutdownNow();
}
} catch (InterruptedException e) {
logger.warn("InstanceInfoReplicator stop interrupted");
}
}
代码示例来源:origin: stackoverflow.com
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Task());
System.out.println(future.get(3, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException e) {
executor.shutdownNow();
代码示例来源:origin: junit-team/junit4
public void run() {
ExecutorService service = Executors.newSingleThreadExecutor();
Callable<Object> callable = new Callable<Object>() {
public Object call() throws Exception {
runTestMethod();
return null;
}
};
Future<Object> result = service.submit(callable);
service.shutdown();
try {
boolean terminated = service.awaitTermination(timeout,
TimeUnit.MILLISECONDS);
if (!terminated) {
service.shutdownNow();
}
result.get(0, TimeUnit.MILLISECONDS); // throws the exception if one occurred during the invocation
} catch (TimeoutException e) {
addFailure(new TestTimedOutException(timeout, TimeUnit.MILLISECONDS));
} catch (Exception e) {
addFailure(e);
}
}
});
代码示例来源:origin: apache/hive
@Test
public void testGetInputSummaryPool() throws ExecutionException, InterruptedException, IOException {
ExecutorService pool = mock(ExecutorService.class);
when(pool.submit(any(Runnable.class))).thenReturn(mock(Future.class));
Set<Path> pathNeedProcess = new HashSet<>();
pathNeedProcess.add(new Path("dummy-path1"));
pathNeedProcess.add(new Path("dummy-path2"));
pathNeedProcess.add(new Path("dummy-path3"));
SessionState.start(new HiveConf());
JobConf jobConf = new JobConf();
Context context = new Context(jobConf);
Utilities.getInputSummaryWithPool(context, pathNeedProcess, mock(MapWork.class), new long[3], pool);
verify(pool, times(3)).submit(any(Runnable.class));
verify(pool).shutdown();
verify(pool).shutdownNow();
}
代码示例来源:origin: prestodb/presto
queryExecutor.submit(() -> {
try {
statement.execute("SELECT 1 AS col1 FROM tpch.sf1.lineitem CROSS JOIN tpch.sf1.lineitem");
queryExecutor.shutdownNow();
代码示例来源:origin: apache/storm
@Override
public void close() throws IOException {
this.active = false;
this.service.shutdownNow();
try {
this.service.awaitTermination(1L, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOG.error("Failed to close assignments distribute service");
}
this.assignmentsQueue = null;
}
代码示例来源:origin: reactive-streams/reactive-streams-jvm
@Test
public void required_spec317_mustSupportAPendingElementCountUpToLongMaxValue_shouldFail_onAsynchDemandIgnoringPublisher() throws Throwable {
// 10 is arbitrary here, we just need a "larger number" to get into concurrent access scenarios, anything more than 2
// should work, but getting up to 10 should be safer and doesn't hurt to play safe here
final ExecutorService pool = Executors.newFixedThreadPool(10);
try {
requireTestFailure(new ThrowingRunnable() {
@Override public void run() throws Throwable {
demandIgnoringAsynchronousPublisherVerification(pool).required_spec317_mustSupportAPendingElementCountUpToLongMaxValue();
}
}, "Expected end-of-stream but got");
} finally {
pool.shutdownNow();
pool.awaitTermination(1, TimeUnit.SECONDS);
}
}
内容来源于网络,如有侵权,请联系作者删除!