Skip to content

Commit

Permalink
[guice] Adding CloseableSingleton scope
Browse files Browse the repository at this point in the history
  • Loading branch information
denis-itskovich committed Feb 4, 2020
1 parent a55a1ac commit 532d73c
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,9 @@
import com.google.inject.Binder;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.slimgears.util.stream.Optionals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;
import java.util.Stack;

public class CloseableSingletonScope extends AbstractScope implements AutoCloseable {
private final Logger log = LoggerFactory.getLogger(CloseableSingletonScope.class);
private final ObjectStorage objectStorage = new ObjectStorage();
private final Stack<AutoCloseable> closeables = new Stack<>();

public static void install(Binder binder) {
CloseableSingletonScope scope = new CloseableSingletonScope();
Expand All @@ -22,14 +14,6 @@ public static void install(Binder binder) {
}

private CloseableSingletonScope() {
objectStorage.subscribe(new ObjectStorage.InstantiationListener() {
@Override
public <T> void onInstantiated(Key<T> key, T instance) {
Optional.ofNullable(instance)
.flatMap(Optionals.ofType(AutoCloseable.class))
.ifPresent(closeables::push);
}
});
}

@Override
Expand All @@ -39,13 +23,6 @@ protected <T> T provide(Key<T> key, Provider<T> unscopedProvider) {

@Override
public void close() {
while (!closeables.empty()) {
AutoCloseable closeable = closeables.pop();
try {
closeable.close();
} catch (Exception e) {
log.warn("Exception occurred when trying to close {}: ", closeable.getClass().getSimpleName(), e);
}
}
objectStorage.close();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@ public void close() {
AutoCloseable closeable = closeables.pop();
try {
closeable.close();
LOG.debug("{} was closed", closeable.getClass());
} catch (Exception e) {
LOG.error("Error occurred when closing " + closeable.getClass(), e);
LOG.error("Error occurred when closing {}", closeable.getClass(), e);
}
}
}
Expand Down

0 comments on commit 532d73c

Please sign in to comment.