From 93ae3c741b2932fa377cd13685673f24eaee8314 Mon Sep 17 00:00:00 2001 From: Oleg Kalnichevski Date: Thu, 13 Feb 2014 14:10:27 +0000 Subject: [PATCH] Use AtomicBoolean to hold storage status git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1567934 13f79535-47bb-0310-9956-ffa450edef68 --- .../client/cache/ManagedHttpCacheStorage.java | 42 +++++++++---------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/httpclient-cache/src/main/java/org/apache/http/impl/client/cache/ManagedHttpCacheStorage.java b/httpclient-cache/src/main/java/org/apache/http/impl/client/cache/ManagedHttpCacheStorage.java index 39239c76b..1d2372050 100644 --- a/httpclient-cache/src/main/java/org/apache/http/impl/client/cache/ManagedHttpCacheStorage.java +++ b/httpclient-cache/src/main/java/org/apache/http/impl/client/cache/ManagedHttpCacheStorage.java @@ -31,6 +31,7 @@ import java.io.IOException; import java.lang.ref.ReferenceQueue; import java.util.HashSet; import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.http.annotation.ThreadSafe; import org.apache.http.client.cache.HttpCacheEntry; @@ -60,18 +61,18 @@ public class ManagedHttpCacheStorage implements HttpCacheStorage, Closeable { private final CacheMap entries; private final ReferenceQueue morque; private final Set resources; - - private volatile boolean shutdown; + private final AtomicBoolean active; public ManagedHttpCacheStorage(final CacheConfig config) { super(); this.entries = new CacheMap(config.getMaxCacheEntries()); this.morque = new ReferenceQueue(); this.resources = new HashSet(); + this.active = new AtomicBoolean(true); } private void ensureValidState() throws IllegalStateException { - if (this.shutdown) { + if (!this.active.get()) { throw new IllegalStateException("Cache has been shut down"); } } @@ -134,30 +135,27 @@ public class ManagedHttpCacheStorage implements HttpCacheStorage, Closeable { } public void cleanResources() { - if (this.shutdown) { - return; - } - ResourceReference ref; - while ((ref = (ResourceReference) this.morque.poll()) != null) { - synchronized (this) { - this.resources.remove(ref); + if (this.active.get()) { + ResourceReference ref; + while ((ref = (ResourceReference) this.morque.poll()) != null) { + synchronized (this) { + this.resources.remove(ref); + } + ref.getResource().dispose(); } - ref.getResource().dispose(); } } public void shutdown() { - if (this.shutdown) { - return; - } - this.shutdown = true; - synchronized (this) { - this.entries.clear(); - for (final ResourceReference ref: this.resources) { - ref.getResource().dispose(); - } - this.resources.clear(); - while (this.morque.poll() != null) { + if (this.active.compareAndSet(true, false)) { + synchronized (this) { + this.entries.clear(); + for (final ResourceReference ref: this.resources) { + ref.getResource().dispose(); + } + this.resources.clear(); + while (this.morque.poll() != null) { + } } } }