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

The following examples show how to use java.util.concurrent.Executors#unconfigurableScheduledExecutorService() . 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
Source File: ExecutorsTest.java    From openjdk-jdk9 with GNU General Public License v2.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 2
Source File: EventSchedulerService.java    From flux with 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 File: ExecutorsTest.java    From j2objc with 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
Source File: ScheduledExecutorFactoryBean.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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
Source File: ScheduledExecutorFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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
Source File: ScheduledExecutorFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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
Source File: ExecutorsTest.java    From openjdk-jdk9 with GNU General Public License v2.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 8
Source File: ScheduledExecutorFactoryBean.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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
Source File: MoreExecutors.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 File: ExecutorsTest.java    From j2objc with 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
Source File: ReconnectSchedulerProvider.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@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 File: ClientListService.java    From RCT with 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
Source File: MoreExecutors.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
final ScheduledExecutorService getExitingScheduledExecutorService(ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
  useDaemonThreadFactory(executor);
  ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor);
  addDelayedShutdownHook(service, terminationTimeout, timeUnit);
  return service;
}
 
Example 14
Source File: MoreExecutors.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
final ScheduledExecutorService getExitingScheduledExecutorService(ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
  useDaemonThreadFactory(executor);
  ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor);
  addDelayedShutdownHook(service, terminationTimeout, timeUnit);
  return service;
}
 
Example 15
Source File: MoreExecutors.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
final ScheduledExecutorService getExitingScheduledExecutorService(ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
  useDaemonThreadFactory(executor);
  ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor);
  addDelayedShutdownHook(service, terminationTimeout, timeUnit);
  return service;
}
 
Example 16
Source File: MoreExecutors.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
final ScheduledExecutorService getExitingScheduledExecutorService(ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
  useDaemonThreadFactory(executor);
  ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor);
  addDelayedShutdownHook(service, terminationTimeout, timeUnit);
  return service;
}