Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions core/src/main/java/io/grpc/internal/SharedResourceHolder.java
Original file line number Diff line number Diff line change
Expand Up @@ -134,18 +134,16 @@ synchronized <T> T releaseInternal(final Resource<T> resource, final T instance)
public void run() {
synchronized (SharedResourceHolder.this) {
// Refcount may have gone up since the task was scheduled. Re-check it.
if (cached.refcount == 0) {
try {
resource.close(instance);
} finally {
instances.remove(resource);
if (instances.isEmpty()) {
destroyer.shutdown();
destroyer = null;
}
}
if (cached.refcount != 0) {
return;
}
instances.remove(resource);
if (instances.isEmpty()) {
destroyer.shutdown();
destroyer = null;
}
}
resource.close(instance);
}
}), DESTROY_DELAY_SECONDS, TimeUnit.SECONDS);
}
Expand Down
42 changes: 42 additions & 0 deletions core/src/test/java/io/grpc/internal/SharedResourceHolderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@

import io.grpc.internal.SharedResourceHolder.Resource;
import java.util.LinkedList;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Delayed;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -201,6 +203,46 @@ public void close(ResourceInstance instance) {
assertNotSame(instance, holder.getInternal(resource));
}

@Test(timeout = 5000)
public void closeRunsConcurrently() throws Exception {
CyclicBarrier barrier = new CyclicBarrier(2);
class SlowResource implements Resource<ResourceInstance> {
@Override
public ResourceInstance create() {
return new ResourceInstance();
}

@Override
public void close(ResourceInstance instance) {
instance.closed = true;
try {
barrier.await();
barrier.await();
} catch (Exception ex) {
throw new AssertionError(ex);
}
}
}

Resource<ResourceInstance> resource = new SlowResource();
ResourceInstance instance = holder.getInternal(resource);
holder.releaseInternal(resource, instance);
MockScheduledFuture<?> scheduledDestroyTask = scheduledDestroyTasks.poll();
FutureTask<Void> runTask = new FutureTask<>(scheduledDestroyTask::runTask, null);
Thread t = new Thread(runTask);
t.start();

barrier.await(); // Ensure the other thread has blocked
assertTrue(instance.closed);
instance = holder.getInternal(resource);
assertFalse(instance.closed);
holder.releaseInternal(resource, instance);

barrier.await(); // Resume the other thread
t.join();
runTask.get(); // Check for exception
}

private class MockExecutorFactory implements
SharedResourceHolder.ScheduledExecutorFactory {
@Override
Expand Down