Created
February 14, 2017 19:45
-
-
Save injeniero/4c343b76ae168481774c37f0c5af9272 to your computer and use it in GitHub Desktop.
Dispose managed objects in reverse creation order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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