Referenced from a thread on StackOverflow: https://stackoverflow.com/a/4522411
package org.some.name.here;
import java.util.concurrent.LinkedBlockingQueue;
/*
* Retrieved from https://stackoverflow.com/a/4522411
*
* Important to note that this has a limitation that corePoolSize == maxPoolSize.
* It will not add additional workers beyond the core pool.
*
* Usage:
@Bean
public Executor asyncExecutor() {
LimitedQueue<Runnable> blockingQueue = new LimitedQueue<>(20);
RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
return new ConcurrentTaskExecutor(
new ThreadPoolExecutor(20, 20, 0L, TimeUnit.MILLISECONDS, blockingQueue, rejectedExecutionHandler));
}
*
*/
public class LimitedQueue<E> extends LinkedBlockingQueue<E> {
private static final long serialVersionUID = 1809662594636042127L;
public LimitedQueue(int maxSize) {
super(maxSize);
}
@Override
public boolean offer(E e) {
// turn offer() and add() into a blocking calls (unless interrupted)
try {
put(e);
return true;
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
return false;
}
}