Last active
August 29, 2015 14:07
-
-
Save chuanwang66/17f649ecaf565cfeea82 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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