Skip to content

Instantly share code, notes, and snippets.

@trK54Ylmz
Last active November 27, 2015 20:43
Show Gist options
  • Save trK54Ylmz/fac19dd8059880268688 to your computer and use it in GitHub Desktop.
Save trK54Ylmz/fac19dd8059880268688 to your computer and use it in GitHub Desktop.
Simple thread pool with rejected execution - log4j required
/*
* Copyright 2015 Tarık Yılmaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
import org.apache.log4j.Logger;
import java.util.concurrent.*;
public class ThreadPool
{
private static final Logger logger = Logger.getLogger(ThreadPool.class);
private ThreadPoolExecutor executor;
private int threadSize;
private int queueSize;
public void setThreadSize(int threadSize) {
this.threadSize = threadSize;
}
public void setQueueSize(int queueSize) {
this.queueSize = queueSize;
}
public void createThreadPool() {
if (threadSize == 0) {
threadSize = Runtime.getRuntime().availableProcessors();
}
if (queueSize == 0) queueSize = 200;
final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(queueSize);
executor = new ThreadPoolExecutor(threadSize, threadSize, 1L, TimeUnit.HOURS, queue);
executor.setRejectedExecutionHandler(new RejectedExecutionHandler()
{
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
Thread.sleep(2000);
queue.put(r);
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
});
}
public int getActiveThread() {
return executor.getQueue().size();
}
public void execute(Runnable r) {
executor.execute(r);
}
public <T> T submit(Runnable runnable, T type) {
try {
Future<T> future = executor.submit(runnable, type);
return future.get();
} catch (ExecutionException | InterruptedException e) {
logger.error(e.getMessage(), e);
}
return null;
}
public void stop() {
executor.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment