当前位置: 首页>>代码示例>>Java>>正文


Java ScheduledExecutorService.shutdownNow方法代码示例

本文整理汇总了Java中java.util.concurrent.ScheduledExecutorService.shutdownNow方法的典型用法代码示例。如果您正苦于以下问题:Java ScheduledExecutorService.shutdownNow方法的具体用法?Java ScheduledExecutorService.shutdownNow怎么用?Java ScheduledExecutorService.shutdownNow使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.concurrent.ScheduledExecutorService的用法示例。


在下文中一共展示了ScheduledExecutorService.shutdownNow方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: killTasks

import java.util.concurrent.ScheduledExecutorService; //导入方法依赖的package包/类
public static void killTasks(final String name) {
    final ScheduledExecutorService executorService = getBackgroundExecutor(name);
    executorService.shutdownNow();
    try {
        executorService.awaitTermination(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        Log.wtf(TAG, "Failed to shut down: " + name);
    }
    if (executorService == sExecutorServiceForTests) {
        // Don't do anything to the test service.
        return;
    }
    switch (name) {
        case KEYBOARD:
            sKeyboardExecutorService = newExecutorService(KEYBOARD);
            break;
        case SPELLING:
            sSpellingExecutorService = newExecutorService(SPELLING);
            break;
        default:
            throw new IllegalArgumentException("Invalid executor: " + name);
    }
}
 
开发者ID:sergeychilingaryan,项目名称:AOSP-Kayboard-7.1.2,代码行数:24,代码来源:ExecutorUtils.java

示例2: stopSendThread

import java.util.concurrent.ScheduledExecutorService; //导入方法依赖的package包/类
private void stopSendThread(Application application)
{
    if (application == null)
    {
        WebtrekkLogging.log("Error unregister callback. Application reference is null");
        return;
    }

    if (!Webtrekk.getInstance().isInitialized())
    {
        WebtrekkLogging.log("Error unregister callback. Webtrekk isn't initialized");
        return;
    }
    Webtrekk webtrekk = Webtrekk.getInstance();

    RequestFactory requestFactory = (RequestFactory)returnHiddenField(webtrekk, "mRequestFactory");
    ScheduledExecutorService threadService1 = (ScheduledExecutorService)returnHiddenField(requestFactory, "mURLSendTimerService");
    ScheduledExecutorService threadService2 = (ScheduledExecutorService)returnHiddenField(requestFactory, "mFlashTimerService");
    threadService1.shutdownNow();
    threadService2.shutdownNow();
}
 
开发者ID:Webtrekk,项目名称:webtrekk-android-sdk,代码行数:22,代码来源:SDKInstanceManager.java

示例3: shutdown

import java.util.concurrent.ScheduledExecutorService; //导入方法依赖的package包/类
public static void shutdown(ScheduledExecutorService executor, long timeoutMillis) {
	if (executor == null) {
		return;
	}
	executor.shutdownNow();
	boolean cleanlyTerminated;
	try {
		cleanlyTerminated = executor.awaitTermination(timeoutMillis, TimeUnit.MILLISECONDS);
	} catch (InterruptedException e) {
		Thread.currentThread().interrupt();
		cleanlyTerminated = executor.isTerminated();
	}
	if (!cleanlyTerminated) {
		String threadpoolName;
		if (executor instanceof ScheduledThreadPoolExecutor) {
			ThreadFactory factory = ((ScheduledThreadPoolExecutor) executor).getThreadFactory();
			if (factory instanceof NamingThreadFactory) {
				NamingThreadFactory namingFactory = (NamingThreadFactory) factory;
				threadpoolName = namingFactory.getPrefix();
			} else {
				threadpoolName = "unknown[" + factory.getClass().getSimpleName() + "]";
			}
		} else {
			threadpoolName = "unknown[" + executor.getClass().getSimpleName() + "]";
		}
		LOG.error("executor did not terminate in the specified time: " + threadpoolName);
	}
}
 
开发者ID:dernasherbrezon,项目名称:r2cloud,代码行数:29,代码来源:Util.java

示例4: start

import java.util.concurrent.ScheduledExecutorService; //导入方法依赖的package包/类
public void start() {
    int count = Runtime.getRuntime().availableProcessors();
    if (count > 4) {
        count /= 2;
    }
    if (count > 8) {
        count = 8;
    }
    ScheduledExecutorService exec = Executors.newScheduledThreadPool(count, THREAD_FACTORY);
    if (!this.executor.compareAndSet(NONE, exec)) {
        exec.shutdownNow();
    } else if (!NewThreadWorker.tryEnableCancelPolicy(exec) && (exec instanceof ScheduledThreadPoolExecutor)) {
        NewThreadWorker.registerExecutor((ScheduledThreadPoolExecutor) exec);
    }
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:16,代码来源:GenericScheduledExecutorService.java

示例5: registerExecutor

import java.util.concurrent.ScheduledExecutorService; //导入方法依赖的package包/类
public static void registerExecutor(ScheduledThreadPoolExecutor service) {
    while (((ScheduledExecutorService) PURGE.get()) == null) {
        ScheduledExecutorService exec = Executors.newScheduledThreadPool(1, new RxThreadFactory(PURGE_THREAD_PREFIX));
        if (PURGE.compareAndSet(null, exec)) {
            exec.scheduleAtFixedRate(new Runnable() {
                public void run() {
                    NewThreadWorker.purgeExecutors();
                }
            }, (long) PURGE_FREQUENCY, (long) PURGE_FREQUENCY, TimeUnit.MILLISECONDS);
            break;
        }
        exec.shutdownNow();
    }
    EXECUTORS.putIfAbsent(service, service);
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:16,代码来源:NewThreadWorker.java

示例6: syncLogsShutdown

import java.util.concurrent.ScheduledExecutorService; //导入方法依赖的package包/类
public static synchronized void syncLogsShutdown(
  ScheduledExecutorService scheduler) 
{
  // flush standard streams
  //
  System.out.flush();
  System.err.flush();

  if (scheduler != null) {
    scheduler.shutdownNow();
  }

  // flush & close all appenders
  LogManager.shutdown(); 
}
 
开发者ID:naver,项目名称:hadoop,代码行数:16,代码来源:TaskLog.java

示例7: testMetricCacheUpdateRace

import java.util.concurrent.ScheduledExecutorService; //导入方法依赖的package包/类
/**
 * Test a race condition when updating the JMX cache (HADOOP-12482):
 * 1. Thread A reads the JMX metric every 2 JMX cache TTL. It marks the JMX
 *    cache to be updated by marking lastRecs to null. After this it adds a
 *    new key to the metrics. The next call to read should pick up this new
 *    key.
 * 2. Thread B triggers JMX metric update every 1 JMX cache TTL. It assigns
 *    lastRecs to a new object (not null any more).
 * 3. Thread A tries to read JMX metric again, sees lastRecs is not null and
 *    does not update JMX cache. As a result the read does not pickup the new
 *    metric.
 * @throws Exception
 */
@Test
public void testMetricCacheUpdateRace() throws Exception {
  // Create test source with a single metric counter of value 1.
  TestMetricsSource source = new TestMetricsSource();
  MetricsSourceBuilder sourceBuilder =
      MetricsAnnotations.newSourceBuilder(source);

  final long JMX_CACHE_TTL = 250; // ms
  List<MetricsTag> injectedTags = new ArrayList<>();
  MetricsSourceAdapter sourceAdapter =
      new MetricsSourceAdapter("test", "test",
          "test JMX cache update race condition", sourceBuilder.build(),
          injectedTags, null, null, JMX_CACHE_TTL, false);

  ScheduledExecutorService updaterExecutor =
      Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().build());
  ScheduledExecutorService readerExecutor =
      Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().build());

  final AtomicBoolean hasError = new AtomicBoolean(false);

  // Wake up every 1 JMX cache TTL to set lastRecs before updateJmxCache() is
  // called.
  SourceUpdater srcUpdater = new SourceUpdater(sourceAdapter, hasError);
  ScheduledFuture<?> updaterFuture =
      updaterExecutor.scheduleAtFixedRate(srcUpdater,
          sourceAdapter.getJmxCacheTTL(), sourceAdapter.getJmxCacheTTL(),
          TimeUnit.MILLISECONDS);
  srcUpdater.setFuture(updaterFuture);

  // Wake up every 2 JMX cache TTL so updateJmxCache() will try to update
  // JMX cache.
  SourceReader srcReader = new SourceReader(source, sourceAdapter, hasError);
  ScheduledFuture<?> readerFuture =
      readerExecutor.scheduleAtFixedRate(srcReader,
          0, // set JMX info cache at the beginning
          2 * sourceAdapter.getJmxCacheTTL(), TimeUnit.MILLISECONDS);
  srcReader.setFuture(readerFuture);

  // Let the threads do their work.
  Thread.sleep(RACE_TEST_RUNTIME);

  assertFalse("Hit error", hasError.get());

  // cleanup
  updaterExecutor.shutdownNow();
  readerExecutor.shutdownNow();
  updaterExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS);
  readerExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS);
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:64,代码来源:TestMetricsSourceAdapter.java

示例8: retryIn

import java.util.concurrent.ScheduledExecutorService; //导入方法依赖的package包/类
protected void retryIn(final int seconds, final Runnable consumer) {
    LOGGER.info("Retry fetching url in {}seconds", seconds);
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    executor.schedule(consumer, seconds, TimeUnit.SECONDS);
    executor.shutdownNow();
}
 
开发者ID:dethi,项目名称:guereza,代码行数:7,代码来源:App.java

示例9: testWakeupWithFetchDataAvailable

import java.util.concurrent.ScheduledExecutorService; //导入方法依赖的package包/类
@Test
public void testWakeupWithFetchDataAvailable() throws Exception {
    int rebalanceTimeoutMs = 60000;
    final int sessionTimeoutMs = 30000;
    int heartbeatIntervalMs = 3000;

    // adjust auto commit interval lower than heartbeat so we don't need to deal with
    // a concurrent heartbeat request
    int autoCommitIntervalMs = 1000;

    final Time time = new MockTime();
    Cluster cluster = TestUtils.singletonCluster(topic, 1);
    Node node = cluster.nodes().get(0);

    Metadata metadata = createMetadata();
    metadata.update(cluster, Collections.<String>emptySet(), time.milliseconds());

    MockClient client = new MockClient(time, metadata);
    client.setNode(node);
    PartitionAssignor assignor = new RoundRobinAssignor();

    final KafkaConsumer<String, String> consumer = newConsumer(time, client, metadata, assignor,
            rebalanceTimeoutMs, sessionTimeoutMs, heartbeatIntervalMs, true, autoCommitIntervalMs);

    consumer.subscribe(Arrays.asList(topic), getConsumerRebalanceListener(consumer));
    prepareRebalance(client, node, assignor, Arrays.asList(tp0), null);

    consumer.poll(0);

    // respond to the outstanding fetch so that we have data available on the next poll
    client.respondFrom(fetchResponse(tp0, 0, 5), node);
    client.poll(0, time.milliseconds());

    consumer.wakeup();

    try {
        consumer.poll(0);
        fail();
    } catch (WakeupException e) {
    }

    // make sure the position hasn't been updated
    assertEquals(0, consumer.position(tp0));

    // the next poll should return the completed fetch
    ConsumerRecords<String, String> records = consumer.poll(0);
    assertEquals(5, records.count());
    // Increment time asynchronously to clear timeouts in closing the consumer
    final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            time.sleep(sessionTimeoutMs);
        }
    }, 0L, 10L, TimeUnit.MILLISECONDS);
    consumer.close();
    exec.shutdownNow();
    exec.awaitTermination(5L, TimeUnit.SECONDS);
}
 
开发者ID:YMCoding,项目名称:kafka-0.11.0.0-src-with-comment,代码行数:60,代码来源:KafkaConsumerTest.java


注:本文中的java.util.concurrent.ScheduledExecutorService.shutdownNow方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。