Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.bqe;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.RejectedExecutionException;
- import java.util.concurrent.TimeUnit;
- import java.util.concurrent.atomic.AtomicInteger;
- import org.junit.*;
- import static org.junit.Assert.*;
- public class BoundedExecutorServiceTest {
- static final int BOUND = 3;
- static final TimeUnit UNIT = TimeUnit.MILLISECONDS;
- @After public void shutdown() throws InterruptedException {
- testCount.incrementAndGet();
- exec.shutdown();
- exec.awaitTermination(BOUND * 100, UNIT);
- }
- @Test public void acceptsSingleTask() {
- exec.execute(newTask());
- }
- @Test public void rejectsTaskOverLimit() {
- for (int i = 0; i < BOUND; ++i) {
- exec.execute(newTask());
- }
- try {
- exec.execute(newTask());
- fail("task should be rejected");
- } catch (RejectedExecutionException ex) {
- // expected
- }
- }
- @Test public void acceptsTaskOverLimitAfterWait() throws InterruptedException {
- for (int i = 0; i < BOUND; ++i) {
- exec.execute(newTask());
- }
- try {
- UNIT.sleep(100); // wait for one task to finish
- exec.execute(newTask());
- } catch (RejectedExecutionException ex) {
- fail("task should not have been rejected");
- }
- }
- Runnable newTask() {
- return new Runnable() {
- public void run() {
- try {
- System.out.printf("running task %s%n", id);
- UNIT.sleep(100);
- System.out.printf("finished task %s%n", id);
- } catch (InterruptedException ex) {
- Thread.currentThread().interrupt();
- }
- }
- private final String id = String.format("%d-%d",
- testCount.get(), taskCount.incrementAndGet());
- {
- System.out.printf("created task %s%n", id);
- }
- };
- }
- private static AtomicInteger testCount = new AtomicInteger();
- private AtomicInteger taskCount = new AtomicInteger();
- private BoundedExecutorService exec =
- new BoundedExecutorService(Executors.newCachedThreadPool(), BOUND);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement