Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@injeniero
Created February 14, 2017 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save injeniero/4c343b76ae168481774c37f0c5af9272 to your computer and use it in GitHub Desktop.
Save injeniero/4c343b76ae168481774c37f0c5af9272 to your computer and use it in GitHub Desktop.
Dispose managed objects in reverse creation order
/**
* Implementation of the request scope instance.
*/
public static final class Instance {
/**
* A map of injectable instances in this scope.
*/
private final Map<ActiveDescriptor<?>, Object> store;
private Instance() {
//Use a LinkedHashMap to keep insertion order
this.store = new LinkedHashMap<ActiveDescriptor<?>, Object>();
this.referenceCounter = new AtomicInteger(1);
}
/**
* Release a single reference to the current request scope instance.
*
* Once all instance references are released, the instance will be recycled.
*/
public void release() {
if (referenceCounter.decrementAndGet() < 1) {
try {
//Create a reverse order list to remove the objects from last created to first.
List<ActiveDescriptor<?>> keys = Lists.reverse(ImmutableList.copyOf(store.keySet()));
for (final ActiveDescriptor<?> descriptor : keys) {
remove(descriptor);
}
} finally {
logger.debugLog("Released scope instance {0}", this);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment