/** * Tests that an exception is thrown if the timestamps overflows and terminate before 5 seconds. */ @Test public void resourcePoolTimestampOverflow() { Callable<Integer> task = () -> { ConcurrentLinkedQueue<Integer> queue = mock(ConcurrentLinkedQueue.class); TestResourcePool testPool = new TestResourcePool(2, queue); Integer resource1 = testPool.acquire(Long.MAX_VALUE, TimeUnit.MILLISECONDS); Integer resource2 = testPool.acquire(Long.MAX_VALUE, TimeUnit.MILLISECONDS); assertEquals(new Integer(1), resource1); assertEquals(new Integer(2), resource2); Integer resource3 = testPool.acquire(Long.MAX_VALUE, TimeUnit.MILLISECONDS); assertNull(resource3); return resource3; }; ExecutorService executor = Executors.newFixedThreadPool(1); Future<Integer> future = executor.submit(task); boolean timeout = false; try { future.get(5000, TimeUnit.MILLISECONDS); } catch (Exception ex) { timeout = true; } assertTrue(timeout); assertFalse(future.isDone()); future.cancel(true); } }
/** * Tests that an exception is thrown if the resource pool is used more than its size can take. */ @Test public void resourcePoolBlocking() throws InterruptedException { mThrown.expect(RuntimeException.class); final int POOL_SIZE = 2; @SuppressWarnings("unchecked") ConcurrentLinkedQueue<Integer> queue = mock(ConcurrentLinkedQueue.class); TestResourcePool testPool = new TestResourcePool(POOL_SIZE, queue); when(queue.isEmpty()).thenReturn(true); when(queue.poll()).thenThrow(new InterruptedException()); for (int i = 0; i < POOL_SIZE + 1; i++) { testPool.acquire(); } }
/** * Tests the normal acquiration of resource pools. */ @Test public void resourcePoolNormal() { TestResourcePool testPool = new TestResourcePool(2); int resource1 = testPool.acquire(); testPool.release(resource1); int resource2 = testPool.acquire(); assertEquals(resource1, resource2); }