|
30 | 30 |
|
31 | 31 | import io.grpc.internal.SharedResourceHolder.Resource; |
32 | 32 | import java.util.LinkedList; |
| 33 | +import java.util.concurrent.CyclicBarrier; |
33 | 34 | import java.util.concurrent.Delayed; |
| 35 | +import java.util.concurrent.FutureTask; |
34 | 36 | import java.util.concurrent.ScheduledExecutorService; |
35 | 37 | import java.util.concurrent.ScheduledFuture; |
36 | 38 | import java.util.concurrent.TimeUnit; |
@@ -201,6 +203,46 @@ public void close(ResourceInstance instance) { |
201 | 203 | assertNotSame(instance, holder.getInternal(resource)); |
202 | 204 | } |
203 | 205 |
|
| 206 | + @Test(timeout = 5000) |
| 207 | + public void closeRunsConcurrently() throws Exception { |
| 208 | + CyclicBarrier barrier = new CyclicBarrier(2); |
| 209 | + class SlowResource implements Resource<ResourceInstance> { |
| 210 | + @Override |
| 211 | + public ResourceInstance create() { |
| 212 | + return new ResourceInstance(); |
| 213 | + } |
| 214 | + |
| 215 | + @Override |
| 216 | + public void close(ResourceInstance instance) { |
| 217 | + instance.closed = true; |
| 218 | + try { |
| 219 | + barrier.await(); |
| 220 | + barrier.await(); |
| 221 | + } catch (Exception ex) { |
| 222 | + throw new AssertionError(ex); |
| 223 | + } |
| 224 | + } |
| 225 | + } |
| 226 | + |
| 227 | + Resource<ResourceInstance> resource = new SlowResource(); |
| 228 | + ResourceInstance instance = holder.getInternal(resource); |
| 229 | + holder.releaseInternal(resource, instance); |
| 230 | + MockScheduledFuture<?> scheduledDestroyTask = scheduledDestroyTasks.poll(); |
| 231 | + FutureTask<Void> runTask = new FutureTask<>(scheduledDestroyTask::runTask, null); |
| 232 | + Thread t = new Thread(runTask); |
| 233 | + t.start(); |
| 234 | + |
| 235 | + barrier.await(); // Ensure the other thread has blocked |
| 236 | + assertTrue(instance.closed); |
| 237 | + instance = holder.getInternal(resource); |
| 238 | + assertFalse(instance.closed); |
| 239 | + holder.releaseInternal(resource, instance); |
| 240 | + |
| 241 | + barrier.await(); // Resume the other thread |
| 242 | + t.join(); |
| 243 | + runTask.get(); // Check for exception |
| 244 | + } |
| 245 | + |
204 | 246 | private class MockExecutorFactory implements |
205 | 247 | SharedResourceHolder.ScheduledExecutorFactory { |
206 | 248 | @Override |
|
0 commit comments