Java Code Examples for java.util.concurrent.ThreadPoolExecutor#setKeepAliveTime()

The following examples show how to use java.util.concurrent.ThreadPoolExecutor#setKeepAliveTime() . 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: AsyncZuulServlet.java    From s2g-zuul with MIT License 6 votes vote down vote up
@Override
public void init() throws ServletException {
	reNewThreadPool();
    Runnable c = new Runnable() {
        @Override
        public void run() {
            ThreadPoolExecutor p = poolExecutorRef.get();
            p.setCorePoolSize(coreSize.get());
            p.setMaximumPoolSize(maximumSize.get());
            p.setKeepAliveTime(aliveTime.get(),TimeUnit.MILLISECONDS);
        }
    };
    
    coreSize.addCallback(c);
    maximumSize.addCallback(c);
    aliveTime.addCallback(c);
    
    // TODO metrics reporting
}
 
Example 2
Source File: WorldRendererCanvas.java    From BlockMap with MIT License 5 votes vote down vote up
public WorldRendererCanvas() {
	{// Executor
		executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(THREAD_COUNT);
		executor.setKeepAliveTime(20, TimeUnit.SECONDS);
		executor.allowCoreThreadTimeOut(true);
	}

	progress.addListener(e -> repaint());

	this.regionFolder.addListener((obs, prev, val) -> {
		if (val == null || val.listRegions().isEmpty()) {
			map = null;
			status.set("No regions loaded");
			chunkMetadata.unbind();
			chunkMetadata.clear();
		} else {
			map = new RenderedMap(val, executor, viewport.mouseWorldProperty);
			map.getCurrentlyRendering().addListener((InvalidationListener) e -> repaint());
			progress.bind(map.getProgress());
			chunkMetadata.bind(map.getChunkMetadata());
			status.set("Rendering");
			executor.execute(() -> Platform.runLater(() -> status.set("Done")));
		}
		repaint();
	});
	this.regionFolder.set(null);

	viewport.widthProperty.bind(widthProperty());
	viewport.heightProperty.bind(heightProperty());
	viewport.frustumProperty.addListener(e -> repaint());

	repaint();
}
 
Example 3
Source File: Test_ThreadsManager.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void positiveTest() {

    // create the threads manager
    this.threadsManager = new ThreadsManager();

    // create all the threads
    ThreadPoolExecutor executor = ( ThreadPoolExecutor ) Executors.newCachedThreadPool();
    executor.setKeepAliveTime( 0, TimeUnit.SECONDS );
    ExecutorCompletionService<Object> executionService = new ExecutorCompletionService<Object>( executor );

    IterationListener listener = new IterationListener();

    msg( log, "Ask Java to create all threads" );
    for( int j = 0; j < N_THREADS; j++ ) {
        executionService.submit( new TestWorker( N_ITERATIONS, threadsManager, listener ), null );
    }

    // run all iterations
    for( int i = 0; i < N_ITERATIONS; i++ ) {
        msg( log, "ITERATION " + i + "\n\n" );
        runThisIteration();

        waitForIterationCompletion();
    }

    // it may take a little while all threads are gone
    try {
        Thread.sleep( 1000 );
    } catch( InterruptedException e ) {}

    // check if there are any remaining threads started by this test
    checkAllRemainingThreads();
}
 
Example 4
Source File: ThreadPoolExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * setKeepAliveTime throws IllegalArgumentException
 * when given a negative value
 */
public void testKeepAliveTimeIllegalArgumentException() {
    final ThreadPoolExecutor p =
        new ThreadPoolExecutor(2, 3,
                               LONG_DELAY_MS, MILLISECONDS,
                               new ArrayBlockingQueue<Runnable>(10));
    try (PoolCleaner cleaner = cleaner(p)) {
        try {
            p.setKeepAliveTime(-1, MILLISECONDS);
            shouldThrow();
        } catch (IllegalArgumentException success) {}
    }
}
 
Example 5
Source File: ThreadPoolExecutorSubclassTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * setKeepAliveTime throws IllegalArgumentException
 * when given a negative value
 */
public void testKeepAliveTimeIllegalArgumentException() {
    final ThreadPoolExecutor p =
        new CustomTPE(2, 3,
                      LONG_DELAY_MS, MILLISECONDS,
                      new ArrayBlockingQueue<Runnable>(10));
    try (PoolCleaner cleaner = cleaner(p)) {
        try {
            p.setKeepAliveTime(-1, MILLISECONDS);
            shouldThrow();
        } catch (IllegalArgumentException success) {}
    }
}
 
Example 6
Source File: ThreadPoolReSeter.java    From sumk with Apache License 2.0 5 votes vote down vote up
private void resetThreadPoolSize() {
	if (!ThreadPoolExecutor.class.isInstance(SumkThreadPool.executor())) {
		return;
	}
	ThreadPoolExecutor pool = (ThreadPoolExecutor) SumkThreadPool.executor();
	int size = AppInfo.getInt("sumk.core.threadpool.core", 0);
	if (size > 0 && pool.getCorePoolSize() != size) {
		logger.info("change ThreadPool size from {} to {}", pool.getCorePoolSize(), size);
		pool.setCorePoolSize(size);
	}

	size = AppInfo.getInt("sumk.core.threadpool.max", 0);
	if (size > 0 && pool.getMaximumPoolSize() != size) {
		logger.info("change ThreadPool max size from {} to {}", pool.getMaximumPoolSize(), size);
		pool.setMaximumPoolSize(size);
	}

	size = AppInfo.getInt("sumk.core.threadpool.aliveTime", 0);
	if (size > 0 && pool.getKeepAliveTime(TimeUnit.MILLISECONDS) != size) {
		logger.info("change ThreadPool keepalive time from {} to {}", pool.getKeepAliveTime(TimeUnit.MILLISECONDS),
				size);
		pool.setKeepAliveTime(size, TimeUnit.MILLISECONDS);
	}

	String v = AppInfo.get("sumk.core.threadpool.allowCoreThreadTimeOut", null);
	if (v != null) {
		boolean allowCoreTimeout = "1".equals(v) || "true".equalsIgnoreCase(v);
		if (allowCoreTimeout != pool.allowsCoreThreadTimeOut()) {
			logger.info("change ThreadPool allowsCoreThreadTimeOut from {} to {}", pool.allowsCoreThreadTimeOut(),
					allowCoreTimeout);
			pool.allowCoreThreadTimeOut(allowCoreTimeout);
		}
	}
}
 
Example 7
Source File: ThreadPoolExecutorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * setKeepAliveTime throws IllegalArgumentException
 * when given a negative value
 */
public void testKeepAliveTimeIllegalArgumentException() {
    final ThreadPoolExecutor p =
        new ThreadPoolExecutor(2, 3,
                               LONG_DELAY_MS, MILLISECONDS,
                               new ArrayBlockingQueue<Runnable>(10));
    try (PoolCleaner cleaner = cleaner(p)) {
        try {
            p.setKeepAliveTime(-1, MILLISECONDS);
            shouldThrow();
        } catch (IllegalArgumentException success) {}
    }
}
 
Example 8
Source File: ThreadPoolExecutorSubclassTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * setKeepAliveTime throws IllegalArgumentException
 * when given a negative value
 */
public void testKeepAliveTimeIllegalArgumentException() {
    final ThreadPoolExecutor p =
        new CustomTPE(2, 3,
                      LONG_DELAY_MS, MILLISECONDS,
                      new ArrayBlockingQueue<Runnable>(10));
    try (PoolCleaner cleaner = cleaner(p)) {
        try {
            p.setKeepAliveTime(-1, MILLISECONDS);
            shouldThrow();
        } catch (IllegalArgumentException success) {}
    }
}
 
Example 9
Source File: OakRepositoryFactory.java    From archiva with Apache License 2.0 5 votes vote down vote up
private ExecutorService createExecutor() {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 60L, TimeUnit.SECONDS,
        new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
        private final AtomicInteger counter = new AtomicInteger();
        private final Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                log.warn("Error occurred in asynchronous processing ", e);
            }
        };
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, createName());
            thread.setDaemon(true);
            thread.setPriority(Thread.MIN_PRIORITY);
            thread.setUncaughtExceptionHandler(handler);
            return thread;
        }

        private String createName() {
            return "oak-lucene-" + counter.getAndIncrement();
        }
    });
    executor.setKeepAliveTime(1, TimeUnit.MINUTES);
    executor.allowCoreThreadTimeOut(true);
    return executor;
}
 
Example 10
Source File: RampUpQueueLoader.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void
        scheduleThreads( String caller,
                         boolean isUseSynchronizedIterations ) throws ActionExecutionException,
                                                               ActionTaskLoaderException,
                                                               NoSuchComponentException,
                                                               NoSuchActionException,
                                                               NoCompatibleMethodFoundException,
                                                               ThreadingPatternNotSupportedException {

    //check the state first
    if (state != ActionTaskLoaderState.NOT_STARTED) {
        throw new ActionTaskLoaderException("Cannot schedule load queue " + queueName
                                            + " - it has already been scheduled");
    }

    //create the executor - terminate threads when finished
    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    executor.setKeepAliveTime(0, TimeUnit.SECONDS);

    ExecutorCompletionService<Object> executionService = new ExecutorCompletionService<Object>(executor);

    //synchronization aids
    threadsManagers = new ArrayList<ThreadsManager>();

    // create the thread for managing max iteration length
    int iterationTimeout = startPattern.getIterationTimeout();
    if (iterationTimeout > 0) {
        itManager = new IterationTimeoutManager(iterationTimeout);
    }

    taskFutures = new ArrayList<Future<Object>>();

    for (int i = 0; i < numThreadGroups; i++) {

        //create the thread iterations manager for this group
        ThreadsManager threadsManager = new ThreadsManager();

        int numThreadsInGroup = (i != numThreadGroups - 1)
                                                           ? numThreadsPerStep
                                                           : numThreadsInLastGroup;
        //distribute executions per timeFrame according to the number of threads
        int executionsPerTimeFrame = executionPattern.getExecutionsPerTimeFrame();
        int[] executionsPerTimeFramePerThread = new EvenLoadDistributingUtils().getEvenLoad(executionsPerTimeFrame,
                                                                                            numThreads);
        if (numThreads > executionsPerTimeFrame && executionsPerTimeFrame > 0) {
            throw new ActionTaskLoaderException("We cannot evenly distribute " + executionsPerTimeFrame
                                                + " iterations per time frame to " + numThreads
                                                + " threads. Iterations per time frame must be at least as many as threads!");
        }

        for (int j = 0; j < numThreadsInGroup; j++) {
            Future<Object> taskFuture = executionService.submit(ActionTaskFactory.createTask(caller,
                                                                                             queueName,
                                                                                             executionPattern,
                                                                                             executionsPerTimeFramePerThread[j],
                                                                                             threadsManager,
                                                                                             itManager,
                                                                                             actionRequests,
                                                                                             parameterDataProviders,
                                                                                             defaultTaskListeners,
                                                                                             isUseSynchronizedIterations),
                                                                null);
            taskFutures.add(taskFuture);
        }

        threadsManagers.add(threadsManager);
    }

    state = ActionTaskLoaderState.SCHEDULED;
}