View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.http.impl.client.cache;
28  
29  import java.io.Closeable;
30  import java.io.IOException;
31  import java.lang.ref.ReferenceQueue;
32  import java.util.HashSet;
33  import java.util.Set;
34  import java.util.concurrent.atomic.AtomicBoolean;
35  
36  import org.apache.http.annotation.Contract;
37  import org.apache.http.annotation.ThreadingBehavior;
38  import org.apache.http.client.cache.HttpCacheEntry;
39  import org.apache.http.client.cache.HttpCacheStorage;
40  import org.apache.http.client.cache.HttpCacheUpdateCallback;
41  import org.apache.http.client.cache.Resource;
42  import org.apache.http.util.Args;
43  
44  /**
45   * <p>
46   * {@link HttpCacheStorage} implementation capable of deallocating resources associated with
47   * the cache entries.
48   * <p>
49   * This cache keeps track of cache entries using
50   * {@link java.lang.ref.PhantomReference} and maintains a collection of all resources that
51   * are no longer in use. The cache, however, does not automatically deallocates associated
52   * resources by invoking {@link Resource#dispose()} method. The consumer MUST periodically
53   * call {@link #cleanResources()} method to trigger resource deallocation. The cache can be
54   * permanently shut down using {@link #shutdown()} method. All resources associated with
55   * the entries used by the cache will be deallocated.
56   * </p>
57   * <p>
58   * This {@link HttpCacheStorage} implementation is intended for use with {@link FileResource}
59   * and similar.
60   * </p>
61   * <p>
62   * Compatibility note. Prior to version 4.4 this storage implementation used to dispose of
63   * all resource entries upon {@link #close()}. As of version 4.4 the {@link #close()} method
64   * disposes only of those resources that have been explicitly removed from the cache with
65   * {@link #removeEntry(String)} method.
66   * </p>
67   * <p>
68   * The {@link #shutdown()} ()} method can still be used to shut down the storage and dispose of
69   * all resources currently managed by it.
70   * </p>
71   *
72   * @since 4.1
73   */
74  @Contract(threading = ThreadingBehavior.SAFE)
75  public class ManagedHttpCacheStorage implements HttpCacheStorage, Closeable {
76  
77      private final CacheMap entries;
78      private final ReferenceQueue<HttpCacheEntry> morque;
79      private final Set<ResourceReference> resources;
80      private final AtomicBoolean active;
81  
82      public ManagedHttpCacheStorage(final CacheConfig config) {
83          super();
84          this.entries = new CacheMap(config.getMaxCacheEntries());
85          this.morque = new ReferenceQueue<HttpCacheEntry>();
86          this.resources = new HashSet<ResourceReference>();
87          this.active = new AtomicBoolean(true);
88      }
89  
90      private void ensureValidState() throws IllegalStateException {
91          if (!this.active.get()) {
92              throw new IllegalStateException("Cache has been shut down");
93          }
94      }
95  
96      private void keepResourceReference(final HttpCacheEntry entry) {
97          final Resource resource = entry.getResource();
98          if (resource != null) {
99              // Must deallocate the resource when the entry is no longer in used
100             final ResourceReferenceche/ResourceReference.html#ResourceReference">ResourceReference ref = new ResourceReference(entry, this.morque);
101             this.resources.add(ref);
102         }
103     }
104 
105     @Override
106     public void putEntry(final String url, final HttpCacheEntry entry) throws IOException {
107         Args.notNull(url, "URL");
108         Args.notNull(entry, "Cache entry");
109         ensureValidState();
110         synchronized (this) {
111             this.entries.put(url, entry);
112             keepResourceReference(entry);
113         }
114     }
115 
116     @Override
117     public HttpCacheEntry getEntry(final String url) throws IOException {
118         Args.notNull(url, "URL");
119         ensureValidState();
120         synchronized (this) {
121             return this.entries.get(url);
122         }
123     }
124 
125     @Override
126     public void removeEntry(final String url) throws IOException {
127         Args.notNull(url, "URL");
128         ensureValidState();
129         synchronized (this) {
130             // Cannot deallocate the associated resources immediately as the
131             // cache entry may still be in use
132             this.entries.remove(url);
133         }
134     }
135 
136     @Override
137     public void updateEntry(
138             final String url,
139             final HttpCacheUpdateCallback callback) throws IOException {
140         Args.notNull(url, "URL");
141         Args.notNull(callback, "Callback");
142         ensureValidState();
143         synchronized (this) {
144             final HttpCacheEntry existing = this.entries.get(url);
145             final HttpCacheEntry updated = callback.update(existing);
146             this.entries.put(url, updated);
147             if (existing != updated) {
148                 keepResourceReference(updated);
149             }
150         }
151     }
152 
153     public void cleanResources() {
154         if (this.active.get()) {
155             ResourceReference ref;
156             while ((ref = (ResourceReference) this.morque.poll()) != null) {
157                 synchronized (this) {
158                     this.resources.remove(ref);
159                 }
160                 ref.getResource().dispose();
161             }
162         }
163     }
164 
165     public void shutdown() {
166         if (this.active.compareAndSet(true, false)) {
167             synchronized (this) {
168                 this.entries.clear();
169                 for (final ResourceReference ref: this.resources) {
170                     ref.getResource().dispose();
171                 }
172                 this.resources.clear();
173                 while (this.morque.poll() != null) {
174                 }
175             }
176         }
177     }
178 
179     @Override
180     public void close() {
181         if (this.active.compareAndSet(true, false)) {
182             synchronized (this) {
183                 ResourceReference ref;
184                 while ((ref = (ResourceReference) this.morque.poll()) != null) {
185                     this.resources.remove(ref);
186                     ref.getResource().dispose();
187                 }
188             }
189         }
190     }
191 
192 }