Skip to content

Instantly share code, notes, and snippets.

@chuanwang66
Last active August 29, 2015 14:07
Show Gist options
  • Save chuanwang66/17f649ecaf565cfeea82 to your computer and use it in GitHub Desktop.
Save chuanwang66/17f649ecaf565cfeea82 to your computer and use it in GitHub Desktop.
the following code is quite helpful to penetrate into the secrete of thread pool:
public class BoundedExecutorService {
BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(4);
RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
private ExecutorService executorService = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS,
blockingQueue, rejectedExecutionHandler);
public void execute(Runnable command) {
executorService.submit(command);
}
public void shutdown() {
try {
executorService.awaitTermination(60, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
implementation of array blocking queue, the code is pretty simple but nice:
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
final E[] items = this.items;
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == items.length)
notFull.await();
} catch (InterruptedException ie) {
notFull.signal(); // propagate to non-interrupted thread
throw ie;
}
insert(e);
} finally {
lock.unlock();
}
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == 0)
notEmpty.await();
} catch (InterruptedException ie) {
notEmpty.signal(); // propagate to non-interrupted thread
throw ie;
}
E x = extract();
return x;
} finally {
lock.unlock();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment