本文整理汇总了Java中java.util.concurrent.ExecutorService.awaitTermination方法的典型用法代码示例。如果您正苦于以下问题:Java ExecutorService.awaitTermination方法的具体用法?Java ExecutorService.awaitTermination怎么用?Java ExecutorService.awaitTermination使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.ExecutorService
的用法示例。
在下文中一共展示了ExecutorService.awaitTermination方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: B0_warm_up
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
@Test
public void B0_warm_up() throws InterruptedException {
List<Dummy> result = synchronizedList(new ArrayList<>());
ExecutorService executor = newFixedThreadPool(FIFTEEN_15);
for (int i = 0; i < ONE_MILLION; i++) {
executor.submit(() -> {
String json = randomJsonPool.get(random.nextInt(ONE_MILLION));
Payload<Dummy> payload = JSON.payload().newInstance(json, Dummy.class);
result.add(payload.get());
result.add(gson.fromJson(json, Dummy.class));
});
}
executor.shutdown();
executor.awaitTermination(10, SECONDS);
assertThat(result.size()).isEqualTo(ONE_MILLION * 2);
}
示例2: shutdown
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void shutdown(ExecutorService exec, Duration timeout){
Duration halfTimeout = timeout.dividedBy(2);
long halfTimeoutMs = timeout.toMillis();
logger.info("shutting down {}", exec);
exec.shutdown();
try{
if(!exec.awaitTermination(halfTimeoutMs, TimeUnit.MILLISECONDS)){
logger.warn("{} did not shut down after {}, interrupting", exec, halfTimeout);
exec.shutdownNow();
if(!exec.awaitTermination(halfTimeoutMs, TimeUnit.MILLISECONDS)){
logger.error("could not shut down {} after {}", exec, timeout);
}
}
}catch(InterruptedException e){
logger.warn("interrupted while waiting for {} to shut down", exec);
exec.shutdownNow();
Thread.currentThread().interrupt();
}
}
示例3: stateSetTest
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
@Test
public void stateSetTest() throws InterruptedException {
Network network = EurostagTutorialExample1Factory.create();
StateManager manager = network.getStateManager();
manager.allowStateMultiThreadAccess(true);
assertTrue(manager.getWorkingStateId().equals(StateManager.INITIAL_STATE_ID));
ExecutorService service = Executors.newSingleThreadExecutor();
service.submit(() -> {
try {
manager.setWorkingState(StateManager.INITIAL_STATE_ID);
network.getGenerator("GEN").getTargetP();
} catch (Exception e) {
fail();
}
});
service.shutdown();
service.awaitTermination(1, TimeUnit.MINUTES);
}
示例4: testInterruption
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
@Test
public void testInterruption() throws InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(10);
SequentialQueue<Integer> queue = new SequentialQueue<>(10);
threadPool.submit(Interrupted.unchecked(() -> queue.dequeue()));
threadPool.submit(Interrupted.unchecked(() -> {
for (int i = 0; i < 200; i++) {
queue.dequeue();
}
}));
for (int i = 0; i < 100; i++) {
final int index = i;
threadPool.submit(Interrupted.unchecked(() -> {
queue.enqueue(index, null);
}));
}
queue.enqueueException(100, new ClassCastException());
threadPool.shutdown();
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}
示例5: testGraphCreate
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public List testGraphCreate(String userId, long count, int poolSize, GraphDataObject[] graph, Class serviceClazz) {
ExecutorService executor = Executors.newFixedThreadPool(poolSize);
for (int i = 0; i < count; i++) {
GraphCreateThread tt = new GraphCreateThread(this, userId, graph[i], serviceClazz);
executor.execute(tt);
}
executor.shutdown();
try {
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return getUpdateResponses();
}
示例6: testMultipleClients
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
@Test
public void testMultipleClients() throws Exception {
ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
try {
ExecutorCompletionService<Boolean> ecs =
new ExecutorCompletionService<Boolean>(exec);
for (int i = 0; i < NUM_THREADS; ++i)
ecs.submit(new IdLockTestThread("client_" + i));
for (int i = 0; i < NUM_THREADS; ++i) {
Future<Boolean> result = ecs.take();
assertTrue(result.get());
}
idLock.assertMapEmpty();
} finally {
exec.shutdown();
exec.awaitTermination(5000, TimeUnit.MILLISECONDS);
}
}
示例7: shutdownAndAwaitTermination
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
* Shutdown cordova thread pool. This assumes we are in control of all tasks running
* in the thread pool.
* Additional info: http://developer.android.com/reference/java/util/concurrent/ExecutorService.html
* @param pool Cordova application's thread pool
*/
private void shutdownAndAwaitTermination(ExecutorService pool) {
Log.d(TAG,"Attempting to shutdown cordova threadpool");
if(!pool.isShutdown()){
try {
// Disable new tasks from being submitted
pool.shutdown();
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
System.err.println("Cordova thread pool did not terminate.");
}
}
}
catch (InterruptedException ie) {
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
}
示例8: getList
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/** 根据Id查询(默认类型T) */
public List<T> getList(List<Long> ids) {
List<T> list = InstanceUtil.newArrayList();
if (ids != null) {
for (int i = 0; i < ids.size(); i++) {
list.add(null);
}
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < ids.size(); i++) {
final int index = i;
executorService.execute(new Runnable() {
public void run() {
list.set(index, queryById(ids.get(index)));
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
} catch (InterruptedException e) {
logger.error("awaitTermination", "", e);
}
}
return list;
}
示例9: testDirectExecutorService_awaitTermination_missedSignal
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
* Test for a bug where threads weren't getting signaled when shutdown was called, only when
* tasks completed.
*/
public void testDirectExecutorService_awaitTermination_missedSignal() {
final ExecutorService service = MoreExecutors.newDirectExecutorService();
Thread waiter = new Thread() {
@Override public void run() {
try {
service.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
return;
}
}
};
waiter.start();
awaitTimedWaiting(waiter);
service.shutdown();
Uninterruptibles.joinUninterruptibly(waiter, 10, TimeUnit.SECONDS);
if (waiter.isAlive()) {
waiter.interrupt();
fail("awaitTermination failed to trigger after shutdown()");
}
}
示例10: destroy
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
@Override
public void destroy() throws Exception {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
if (isClose.compareAndSet(false, true)) {
logger.info("HBaseTemplate2.destroy()");
final ExecutorService executor = this.executor;
if (executor != null) {
executor.shutdown();
try {
executor.awaitTermination(DEFAULT_DESTORY_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
long remainingTime = Math.max(DEFAULT_DESTORY_TIMEOUT - stopWatch.stop(), 100);
awaitAsyncPutOpsCleared(remainingTime, 50);
}
}
示例11: main
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void main(String[] arg)
{
// construct the shared object
SimpleArray sharedSimpleArray = new SimpleArray(6);
// create two tasks to write to the shared SimpleArray
ArrayWriter writer1 = new ArrayWriter(1, sharedSimpleArray);
ArrayWriter writer2 = new ArrayWriter(11, sharedSimpleArray);
// execute the tasks with an ExecutorService
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(writer1);
executorService.execute(writer2);
executorService.shutdown();
try
{
// wait 1 minute for both writers to finish executing
boolean tasksEnded =
executorService.awaitTermination(1, TimeUnit.MINUTES);
if (tasksEnded)
{
System.out.printf("%nContents of SimpleArray:%n");
System.out.println(sharedSimpleArray); // print contents
}
else
System.out.println(
"Timed out while waiting for tasks to finish.");
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
示例12: terminate
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
* Returns <code>true</code> if the given service was terminated successfully. If the termination timed out,
* the service is <code>null</code> this method will return <code>false</code>.
*/
public static boolean terminate(ExecutorService service, long timeout, TimeUnit timeUnit) {
if (service != null) {
service.shutdown();
try {
if (service.awaitTermination(timeout, timeUnit)) {
return true;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
service.shutdownNow();
}
return false;
}
示例13: testWrite_MultipleWriters
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
* Test for multiple writers running in separate threads, writing data simultaneously.
*/
@Test
public void testWrite_MultipleWriters() throws RMIException, IOException, InterruptedException {
// System.out.println("MonarchRecordWriterTest.testWrite_MultipleWriters");
final List<String> lines = TestHelper.getResourceAsString(resourceFile);
final Map<String, Integer> expectedMap = new HashMap<String, Integer>(4) {{
put("0", 10);
put("1", 10);
put("2", 10);
put("3", 1);
}};
final int blockSize = 10;
ExecutorService es = Executors.newFixedThreadPool(3);
for (int i = 0; i < 3; i++) {
final String tid = "000_" + i;
es.submit(() -> {
try {
assertOnRecordWriter(lines, expectedMap, tid, blockSize);
} catch (Exception e) {
fail("No exception expected: " + e.getMessage());
}
});
}
es.shutdown();
es.awaitTermination(5, TimeUnit.SECONDS);
if (!es.isTerminated()) {
es.shutdownNow();
}
Configuration conf = new Configuration();
conf.set("monarch.locator.port", testBase.getLocatorPort());
}
示例14: main
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
int count=1;
ExecutorService pool = Executors.newFixedThreadPool(128);
System.out.println("5555555555555555:"+client.connectionPool().connectionCount());
while (count<=10) {
pool.execute(new Runnable() {
@Override
public void run() {
for(int i=0;i<100;i++){
// RequestBody formBody =new FormBody.Builder()
// .add("q",selectSql)
// .build();
// Request request = new Request.Builder()
// .url(QUERY_URL)
// .header("Connection", "close")
// .post(formBody)
// .build();
// client.newCall(request).execute();
MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain");
String postBody = "Hello World";
Request request = new Request.Builder()
.url("http://cc.0071515.com/")
// .header("Connection", "close")
.post(RequestBody.create(MEDIA_TYPE_TEXT, postBody))
.build();
long st = System.currentTimeMillis();
try {
Response response = client.newCall(request).execute();
System.out.println(response.code());
response.close();
} catch (IOException e) {
e.printStackTrace();
}
long et = System.currentTimeMillis();
System.out.println(client.connectionPool().connectionCount());
// System.out.println(et-st);
// client.dispatcher().executorService().shutdown();
// try {
// client.connectionPool().evictAll();
// } catch (Exception e) {
// e.printStackTrace();
// }
// long startTime = System.currentTimeMillis();
// System.currentTimeMillis();
}
}
});
count++;
}
pool.shutdown();
pool.awaitTermination(10, TimeUnit.DAYS);
// if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//
// Headers responseHeaders = response.headers();
// for (int i = 0; i < responseHeaders.size(); i++) {
// System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
// }
//
// System.out.println(response.body().string());
}
示例15: testRemovalNotification_get_basher
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
* Calls get() repeatedly from many different threads, and tests that all of the removed entries
* (removed because of size limits or expiration) trigger appropriate removal notifications.
*/
@GwtIncompatible // QueuingRemovalListener
public void testRemovalNotification_get_basher() throws InterruptedException {
int nTasks = 1000;
int nThreads = 100;
final int getsPerTask = 1000;
final int nUniqueKeys = 10000;
final Random random = new Random(); // Randoms.insecureRandom();
QueuingRemovalListener<String, String> removalListener = queuingRemovalListener();
final AtomicInteger computeCount = new AtomicInteger();
final AtomicInteger exceptionCount = new AtomicInteger();
final AtomicInteger computeNullCount = new AtomicInteger();
CacheLoader<String, String> countingIdentityLoader =
new CacheLoader<String, String>() {
@Override public String load(String key) throws InterruptedException {
int behavior = random.nextInt(4);
if (behavior == 0) { // throw an exception
exceptionCount.incrementAndGet();
throw new RuntimeException("fake exception for test");
} else if (behavior == 1) { // return null
computeNullCount.incrementAndGet();
return null;
} else if (behavior == 2) { // slight delay before returning
Thread.sleep(5);
computeCount.incrementAndGet();
return key;
} else {
computeCount.incrementAndGet();
return key;
}
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.recordStats()
.concurrencyLevel(2)
.expireAfterWrite(100, TimeUnit.MILLISECONDS)
.removalListener(removalListener)
.maximumSize(5000)
.build(countingIdentityLoader);
ExecutorService threadPool = Executors.newFixedThreadPool(nThreads);
for (int i = 0; i < nTasks; i++) {
@SuppressWarnings("unused") // go/futurereturn-lsc
Future<?> possiblyIgnoredError =
threadPool.submit(
new Runnable() {
@Override
public void run() {
for (int j = 0; j < getsPerTask; j++) {
try {
cache.getUnchecked("key" + random.nextInt(nUniqueKeys));
} catch (RuntimeException e) {
}
}
}
});
}
threadPool.shutdown();
threadPool.awaitTermination(300, TimeUnit.SECONDS);
// Since we're not doing any more cache operations, and the cache only expires/evicts when doing
// other operations, the cache and the removal queue won't change from this point on.
// Verify that each received removal notification was valid
for (RemovalNotification<String, String> notification : removalListener) {
assertEquals("Invalid removal notification", notification.getKey(), notification.getValue());
}
CacheStats stats = cache.stats();
assertEquals(removalListener.size(), stats.evictionCount());
assertEquals(computeCount.get(), stats.loadSuccessCount());
assertEquals(exceptionCount.get() + computeNullCount.get(), stats.loadExceptionCount());
// each computed value is still in the cache, or was passed to the removal listener
assertEquals(computeCount.get(), cache.size() + removalListener.size());
}