-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added a simple ResourceMgr for collecting a set of objects that need …
…to be cleaned up
- Loading branch information
Showing
2 changed files
with
95 additions
and
43 deletions.
There are no files selected for viewing
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
45 changes: 45 additions & 0 deletions
45
...-parent/aksw-commons-utils/src/main/java/org/aksw/commons/util/lifecycle/ResourceMgr.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package org.aksw.commons.util.lifecycle; | ||
|
||
import java.util.Collections; | ||
import java.util.IdentityHashMap; | ||
import java.util.Map; | ||
|
||
import org.aksw.commons.util.exception.FinallyRunAll; | ||
import org.aksw.commons.util.exception.FinallyRunAll.ThrowingConsumer; | ||
import org.aksw.commons.util.function.ThrowingRunnable; | ||
|
||
/** | ||
* A class where resources can be added. | ||
* Upon closing the resource manager, all registered resources will be freed. | ||
* | ||
* @implNote | ||
* This implementation closes resources sequentially. | ||
*/ | ||
public class ResourceMgr | ||
implements AutoCloseable | ||
{ | ||
private final Map<Object, ThrowingRunnable> resourceToCloser = | ||
Collections.synchronizedMap(new IdentityHashMap<>()); | ||
|
||
public ResourceMgr() { | ||
super(); | ||
} | ||
|
||
public <T extends AutoCloseable> T register(T closable) { | ||
return register(closable, AutoCloseable::close); | ||
} | ||
|
||
public <T> T register(T obj, ThrowingConsumer<? super T> closer) { | ||
return register(obj, () -> closer.accept(obj)); | ||
} | ||
|
||
public <T> T register(T obj, ThrowingRunnable closeAction) { | ||
resourceToCloser.put(obj, closeAction); | ||
return obj; | ||
} | ||
|
||
@Override | ||
public void close() { | ||
FinallyRunAll.runAll(resourceToCloser.entrySet(), e -> e.getValue().run(), null); | ||
} | ||
} |