Java Code Examples for java.util.concurrent.Executors#unconfigurableScheduledExecutorService()

The following examples show how to use java.util.concurrent.Executors#unconfigurableScheduledExecutorService() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * an unconfigurable newScheduledThreadPool successfully runs delayed task
 */
public void testUnconfigurableScheduledExecutorService() throws Exception {
    final ScheduledExecutorService p =
        Executors.unconfigurableScheduledExecutorService
        (Executors.newScheduledThreadPool(2));
    try (PoolCleaner cleaner = cleaner(p)) {
        final CountDownLatch proceed = new CountDownLatch(1);
        final Runnable task = new CheckedRunnable() {
            public void realRun() {
                await(proceed);
            }};
        long startTime = System.nanoTime();
        Future f = p.schedule(Executors.callable(task, Boolean.TRUE),
                              timeoutMillis(), MILLISECONDS);
        assertFalse(f.isDone());
        proceed.countDown();
        assertSame(Boolean.TRUE, f.get(LONG_DELAY_MS, MILLISECONDS));
        assertSame(Boolean.TRUE, f.get());
        assertTrue(f.isDone());
        assertFalse(f.isCancelled());
        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
    }
}
 
Example 2
Source Project: flux   File: EventSchedulerService.java    License: Apache License 2.0 6 votes vote down vote up
@Inject
public EventSchedulerService(EventSchedulerDao eventSchedulerDao, EventSchedulerRegistry eventSchedulerRegistry,
                             @Named("eventScheduler.batchRead.intervalms") Integer batchReadInterval,
                             @Named("eventScheduler.batchRead.batchSize") Integer batchSize,
                             ObjectMapper objectMapper) {
    this.eventSchedulerDao = eventSchedulerDao;
    this.eventSchedulerRegistry = eventSchedulerRegistry;
    this.batchReadInterval = batchReadInterval;
    this.batchSize = batchSize;
    this.objectMapper = objectMapper;

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    // remove the task from scheduler on cancel
    executor.setRemoveOnCancelPolicy(true);
    scheduledExecutorService =
            new InstrumentedScheduledExecutorService(Executors.unconfigurableScheduledExecutorService(executor),
                    SharedMetricRegistries.getOrCreate(METRIC_REGISTRY_NAME), scheduledExectorSvcName);
}
 
Example 3
Source Project: j2objc   File: ExecutorsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * an unconfigurable newScheduledThreadPool successfully runs delayed task
 */
public void testUnconfigurableScheduledExecutorService() throws Exception {
    final ScheduledExecutorService p =
        Executors.unconfigurableScheduledExecutorService
        (Executors.newScheduledThreadPool(2));
    try (PoolCleaner cleaner = cleaner(p)) {
        final CountDownLatch proceed = new CountDownLatch(1);
        final Runnable task = new CheckedRunnable() {
            public void realRun() {
                await(proceed);
            }};
        long startTime = System.nanoTime();
        Future f = p.schedule(Executors.callable(task, Boolean.TRUE),
                              timeoutMillis(), MILLISECONDS);
        assertFalse(f.isDone());
        proceed.countDown();
        assertSame(Boolean.TRUE, f.get(LONG_DELAY_MS, MILLISECONDS));
        assertSame(Boolean.TRUE, f.get());
        assertTrue(f.isDone());
        assertFalse(f.isCancelled());
        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
    }
}
 
Example 4
@Override
protected ExecutorService initializeExecutor(
		ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {

	ScheduledExecutorService executor =
			createExecutor(this.poolSize, threadFactory, rejectedExecutionHandler);

	if (this.removeOnCancelPolicy) {
		if (executor instanceof ScheduledThreadPoolExecutor) {
			((ScheduledThreadPoolExecutor) executor).setRemoveOnCancelPolicy(true);
		}
		else {
			logger.debug("Could not apply remove-on-cancel policy - not a ScheduledThreadPoolExecutor");
		}
	}

	// Register specified ScheduledExecutorTasks, if necessary.
	if (!ObjectUtils.isEmpty(this.scheduledExecutorTasks)) {
		registerTasks(this.scheduledExecutorTasks, executor);
	}

	// Wrap executor with an unconfigurable decorator.
	this.exposedExecutor = (this.exposeUnconfigurableExecutor ?
			Executors.unconfigurableScheduledExecutorService(executor) : executor);

	return executor;
}
 
Example 5
@Override
protected ExecutorService initializeExecutor(
		ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {

	ScheduledExecutorService executor =
			createExecutor(this.poolSize, threadFactory, rejectedExecutionHandler);

	if (this.removeOnCancelPolicy) {
		if (executor instanceof ScheduledThreadPoolExecutor) {
			((ScheduledThreadPoolExecutor) executor).setRemoveOnCancelPolicy(true);
		}
		else {
			logger.debug("Could not apply remove-on-cancel policy - not a ScheduledThreadPoolExecutor");
		}
	}

	// Register specified ScheduledExecutorTasks, if necessary.
	if (!ObjectUtils.isEmpty(this.scheduledExecutorTasks)) {
		registerTasks(this.scheduledExecutorTasks, executor);
	}

	// Wrap executor with an unconfigurable decorator.
	this.exposedExecutor = (this.exposeUnconfigurableExecutor ?
			Executors.unconfigurableScheduledExecutorService(executor) : executor);

	return executor;
}
 
Example 6
@Override
@UsesJava7
protected ExecutorService initializeExecutor(
		ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {

	ScheduledExecutorService executor =
			createExecutor(this.poolSize, threadFactory, rejectedExecutionHandler);

	if (this.removeOnCancelPolicy) {
		if (setRemoveOnCancelPolicyAvailable && executor instanceof ScheduledThreadPoolExecutor) {
			((ScheduledThreadPoolExecutor) executor).setRemoveOnCancelPolicy(true);
		}
		else {
			logger.info("Could not apply remove-on-cancel policy - not a Java 7+ ScheduledThreadPoolExecutor");
		}
	}

	// Register specified ScheduledExecutorTasks, if necessary.
	if (!ObjectUtils.isEmpty(this.scheduledExecutorTasks)) {
		registerTasks(this.scheduledExecutorTasks, executor);
	}

	// Wrap executor with an unconfigurable decorator.
	this.exposedExecutor = (this.exposeUnconfigurableExecutor ?
			Executors.unconfigurableScheduledExecutorService(executor) : executor);

	return executor;
}
 
Example 7
/**
 * unconfigurableScheduledExecutorService(null) throws NPE
 */
public void testUnconfigurableScheduledExecutorServiceNPE() {
    try {
        ExecutorService e = Executors.unconfigurableScheduledExecutorService(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 8
@Override
@UsesJava7
protected ExecutorService initializeExecutor(
		ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {

	ScheduledExecutorService executor =
			createExecutor(this.poolSize, threadFactory, rejectedExecutionHandler);

	if (this.removeOnCancelPolicy) {
		if (setRemoveOnCancelPolicyAvailable && executor instanceof ScheduledThreadPoolExecutor) {
			((ScheduledThreadPoolExecutor) executor).setRemoveOnCancelPolicy(true);
		}
		else {
			logger.info("Could not apply remove-on-cancel policy - not a Java 7+ ScheduledThreadPoolExecutor");
		}
	}

	// Register specified ScheduledExecutorTasks, if necessary.
	if (!ObjectUtils.isEmpty(this.scheduledExecutorTasks)) {
		registerTasks(this.scheduledExecutorTasks, executor);
	}

	// Wrap executor with an unconfigurable decorator.
	this.exposedExecutor = (this.exposeUnconfigurableExecutor ?
			Executors.unconfigurableScheduledExecutorService(executor) : executor);

	return executor;
}
 
Example 9
final ScheduledExecutorService getExitingScheduledExecutorService(
    ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
  useDaemonThreadFactory(executor);
  ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor);
  addDelayedShutdownHook(service, terminationTimeout, timeUnit);
  return service;
}
 
Example 10
Source Project: j2objc   File: ExecutorsTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * unconfigurableScheduledExecutorService(null) throws NPE
 */
public void testUnconfigurableScheduledExecutorServiceNPE() {
    try {
        ExecutorService e = Executors.unconfigurableScheduledExecutorService(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 11
@Override
    public ScheduledExecutorService get() {
        final PinpointThreadFactory threadFactory = new PinpointThreadFactory("Pinpoint-reconnect-thread");
        final ScheduledThreadPoolExecutor scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1, threadFactory);

        // not recommended
//        LoggingRejectedExecutionHandler reconnectScheduler = new LoggingRejectedExecutionHandler("ReconnectScheduler");
//        scheduler.setRejectedExecutionHandler(reconnectScheduler);


        ScheduledExecutorService scheduledExecutorService = Executors.unconfigurableScheduledExecutorService(scheduler);
        return scheduledExecutorService ;
    }
 
Example 12
Source Project: RCT   File: ClientListService.java    License: Apache License 2.0 4 votes vote down vote up
public JSONObject executeJob(String internal, String timer,String timerUtil, Long id) {
	JSONObject json = new JSONObject();
	long endTimer = System.currentTimeMillis()+(Long.parseLong(timer)*Long.parseLong(timerUtil))*1000;
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			json.put("msg", "job is Running");
			if(System.currentTimeMillis()>= endTimer) {
				AppCache.taskList.get(String.valueOf(id)).forEach((k,v)->{
					ScheduledFuture<?> future = k;
					json.put("msg", "job  over");
					json.put("status", "DONE");
					future.cancel(true);
					AppCache.taskList.remove(String.valueOf(id));
				});
			}else {
				List<Map<String,Object>> maps = clientSearch(String.valueOf(id), "");
				Set<JSONObject> documents = new HashSet<>();
				maps.forEach(res->{
					Map<String,Object> result = (Map<String,Object>)res;
					result.put("TimeStamp", System.currentTimeMillis()); 
					result.put("id", result.get("age")+String.valueOf(id)); 
					JSONObject jsons = JSONObject.parseObject(JSON.toJSONString(result));
					documents.add(jsons);
				});
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					String index = initConfig.getClientIndex() + "-" + sdf.format(new Date());
					try {
						if (documents.size() <= 0) {
							return;
						}
						if(initConfig.isElasticsearchEnable()) {
							ElasticSearchUtil.bulkIndexDocumentByID(index, "rct-clientlist", documents);
						}	
						
					} catch (Exception e) {
						// LOG.error("slowlogToES error .", e);
					}
					
				}
			}
			
	};
	if (service.isShutdown()) {
		service = Executors.unconfigurableScheduledExecutorService(new ScheduledThreadPoolExecutor(1));
	}
	ScheduledFuture<?> task = service.scheduleAtFixedRate(runnable, 0, Long.parseLong(internal), TimeUnit.SECONDS);
	Map<ScheduledFuture<?>,String> map = new HashMap<>();
	JSONObject obj = new JSONObject();
	obj.put("internal", internal);
	obj.put("timer", timer);
	obj.put("timerUtil", timerUtil);
	map.put(task,obj.toJSONString() );
	AppCache.taskList.put(String.valueOf(id), map);
	return json;
}
 
Example 13
final ScheduledExecutorService getExitingScheduledExecutorService(ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
  useDaemonThreadFactory(executor);
  ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor);
  addDelayedShutdownHook(service, terminationTimeout, timeUnit);
  return service;
}
 
Example 14
final ScheduledExecutorService getExitingScheduledExecutorService(ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
  useDaemonThreadFactory(executor);
  ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor);
  addDelayedShutdownHook(service, terminationTimeout, timeUnit);
  return service;
}
 
Example 15
final ScheduledExecutorService getExitingScheduledExecutorService(ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
  useDaemonThreadFactory(executor);
  ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor);
  addDelayedShutdownHook(service, terminationTimeout, timeUnit);
  return service;
}
 
Example 16
final ScheduledExecutorService getExitingScheduledExecutorService(ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
  useDaemonThreadFactory(executor);
  ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor);
  addDelayedShutdownHook(service, terminationTimeout, timeUnit);
  return service;
}