From 532d73c8cfae3cdc018d7971eb63c81b719c059c Mon Sep 17 00:00:00 2001 From: denis-itskovich Date: Tue, 4 Feb 2020 23:39:27 +0200 Subject: [PATCH] [guice] Adding CloseableSingleton scope --- .../util/guice/CloseableSingletonScope.java | 25 +------------------ .../slimgears/util/guice/ObjectStorage.java | 3 ++- 2 files changed, 3 insertions(+), 25 deletions(-) diff --git a/guice-utils/src/main/java/com/slimgears/util/guice/CloseableSingletonScope.java b/guice-utils/src/main/java/com/slimgears/util/guice/CloseableSingletonScope.java index 2e1fafe..8f8fe0a 100644 --- a/guice-utils/src/main/java/com/slimgears/util/guice/CloseableSingletonScope.java +++ b/guice-utils/src/main/java/com/slimgears/util/guice/CloseableSingletonScope.java @@ -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 closeables = new Stack<>(); public static void install(Binder binder) { CloseableSingletonScope scope = new CloseableSingletonScope(); @@ -22,14 +14,6 @@ public static void install(Binder binder) { } private CloseableSingletonScope() { - objectStorage.subscribe(new ObjectStorage.InstantiationListener() { - @Override - public void onInstantiated(Key key, T instance) { - Optional.ofNullable(instance) - .flatMap(Optionals.ofType(AutoCloseable.class)) - .ifPresent(closeables::push); - } - }); } @Override @@ -39,13 +23,6 @@ protected T provide(Key key, Provider 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(); } } diff --git a/guice-utils/src/main/java/com/slimgears/util/guice/ObjectStorage.java b/guice-utils/src/main/java/com/slimgears/util/guice/ObjectStorage.java index 8be03f6..abb74ea 100644 --- a/guice-utils/src/main/java/com/slimgears/util/guice/ObjectStorage.java +++ b/guice-utils/src/main/java/com/slimgears/util/guice/ObjectStorage.java @@ -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); } } }