Java Code Examples for java.util.concurrent.ScheduledExecutorService.shutdownNow()

The following are Jave code examples for showing how to use shutdownNow() of the java.util.concurrent.ScheduledExecutorService class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: AOSP-Kayboard-7.1.2   File: ExecutorUtils.java   Source Code and License Vote up 6 votes
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);
    }
}
 
Example 2
Project: webtrekk-android-sdk   File: SDKInstanceManager.java   Source Code and License Vote up 6 votes
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();
}
 
Example 3
Project: r2cloud   File: Util.java   Source Code and License Vote up 5 votes
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);
	}
}
 
Example 4
Project: boohee_v5.6   File: GenericScheduledExecutorService.java   Source Code and License Vote up 5 votes
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);
    }
}
 
Example 5
Project: boohee_v5.6   File: NewThreadWorker.java   Source Code and License Vote up 5 votes
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);
}
 
Example 6
Project: hadoop   File: TaskLog.java   Source Code and License Vote up 5 votes
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(); 
}
 
Example 7
Project: hadoop-oss   File: TestMetricsSourceAdapter.java   Source Code and License Vote up 4 votes
/**
 * 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);
}
 
Example 8
Project: guereza   File: App.java   Source Code and License Vote up 4 votes
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();
}
 
Example 9
Project: kafka-0.11.0.0-src-with-comment   File: KafkaConsumerTest.java   Source Code and License Vote up 4 votes
@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);
}