/** * Tests the logic to acquire a resource when the pool is not full. */ @Test public void acquireWithCapacity() throws Exception { TestPool pool = new TestPool(DynamicResourcePool.Options.defaultOptions()); List<Resource> resourceList = new ArrayList<>(); for (int i = 0; i < 3; i++) { Resource resource = pool.acquire(); resourceList.add(resource); Assert.assertEquals(i, resource.mInteger.intValue()); } for (Resource resource : resourceList) { pool.release(resource); } Set<Integer> resources = new HashSet<>(); for (int i = 0; i < 3; i++) { Resource resource = pool.acquire(); resources.add(resource.mInteger); } // Make sure we are not creating new resources. for (int i = 0; i < 3; i++) { Assert.assertTrue(resources.contains(i)); } }
/** * Tests the logic that the recently used resource is preferred. */ @Test public void acquireRentlyUsed() throws Exception { ManualClock manualClock = new ManualClock(); TestPool pool = new TestPool(DynamicResourcePool.Options.defaultOptions(), manualClock); List<Resource> resourceList = new ArrayList<>(); resourceList.add(pool.acquire()); resourceList.add(pool.acquire()); resourceList.add(pool.acquire()); pool.release(resourceList.get(2)); pool.release(resourceList.get(0)); manualClock.addTimeMs(1500); pool.release(resourceList.get(1)); for (int i = 0; i < 10; i++) { Resource resource = pool.acquire(); Assert.assertEquals(1, resource.mInteger.intValue()); pool.release(resource); } }
@Test public void gc() throws Exception { ManualClock manualClock = new ManualClock(); TestPool pool = new TestPool( DynamicResourcePool.Options.defaultOptions().setGcIntervalMs(10).setInitialDelayMs(1), manualClock); pool.setGcThresholdInSecs(1); List<Resource> resourceList = new ArrayList<>(); resourceList.add(pool.acquire()); resourceList.add(pool.acquire()); pool.release(resourceList.get(0)); manualClock.addTimeMs(1001); // Sleep 1 second to make sure the GC has run. Thread.sleep(1000); // Resource 0 is gc-ed. Assert.assertEquals(2, pool.acquire().mInteger.intValue()); }
/** * Tests the logic that invalid resource won't be acquired. */ @Test public void UnhealthyResource() throws Exception { TestPool pool = new TestPool(DynamicResourcePool.Options.defaultOptions()); Resource resource = pool.acquire(); Assert.assertEquals(0, resource.mInteger.intValue()); resource.setInteger(Resource.INVALID_RESOURCE); pool.release(resource); resource = pool.acquire(); // The 0-th resource is not acquired because it is unhealthy. Assert.assertEquals(1, resource.mInteger.intValue()); }