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.ThreadSafe;
37  import org.apache.http.client.cache.HttpCacheEntry;
38  import org.apache.http.client.cache.HttpCacheStorage;
39  import org.apache.http.client.cache.HttpCacheUpdateCallback;
40  import org.apache.http.client.cache.Resource;
41  import org.apache.http.util.Args;
42  
43  /**
44   * <p>
45   * {@link HttpCacheStorage} implementation capable of deallocating resources associated with
46   * the cache entries.
47   * <p>
48   * This cache keeps track of cache entries using
49   * {@link java.lang.ref.PhantomReference} and maintains a collection of all resources that
50   * are no longer in use. The cache, however, does not automatically deallocates associated
51   * resources by invoking {@link Resource#dispose()} method. The consumer MUST periodically
52   * call {@link #cleanResources()} method to trigger resource deallocation. The cache can be
53   * permanently shut down using {@link #shutdown()} method. All resources associated with
54   * the entries used by the cache will be deallocated.
55   * </p>
56   * <p>
57   * This {@link HttpCacheStorage} implementation is intended for use with {@link FileResource}
58   * and similar.
59   * </p>
60   * <p>
61   * Compatibility note. Prior to version 4.4 this storage implementation used to dispose of
62   * all resource entries upon {@link #close()}. As of version 4.4 the {@link #close()} method
63   * disposes only of those resources that have been explicitly removed from the cache with
64   * {@link #removeEntry(String)} method.
65   * </p>
66   * <p>
67   * The {@link #shutdown()} ()} method can still be used to shut down the storage and dispose of
68   * all resources currently managed by it.
69   * </p>
70   *
71   * @since 4.1
72   */
73  @ThreadSafe
74  public class ManagedHttpCacheStorage implements HttpCacheStorage, Closeable {
75  
76      private final CacheMap entries;
77      private final ReferenceQueue<HttpCacheEntry> morque;
78      private final Set<ResourceReference> resources;
79      private final AtomicBoolean active;
80  
81      public ManagedHttpCacheStorage(final CacheConfig config) {
82          super();
83          this.entries = new CacheMap(config.getMaxCacheEntries());
84          this.morque = new ReferenceQueue<HttpCacheEntry>();
85          this.resources = new HashSet<ResourceReference>();
86          this.active = new AtomicBoolean(true);
87      }
88  
89      private void ensureValidState() throws IllegalStateException {
90          if (!this.active.get()) {
91              throw new IllegalStateException("Cache has been shut down");
92          }
93      }
94  
95      private void keepResourceReference(final HttpCacheEntry entry) {
96          final Resource resource = entry.getResource();
97          if (resource != null) {
98              // Must deallocate the resource when the entry is no longer in used
99              final ResourceReference ref = new ResourceReference(entry, this.morque);
100             this.resources.add(ref);
101         }
102     }
103 
104     @Override
105     public void putEntry(final String url, final HttpCacheEntry entry) throws IOException {
106         Args.notNull(url, "URL");
107         Args.notNull(entry, "Cache entry");
108         ensureValidState();
109         synchronized (this) {
110             this.entries.put(url, entry);
111             keepResourceReference(entry);
112         }
113     }
114 
115     @Override
116     public HttpCacheEntry getEntry(final String url) throws IOException {
117         Args.notNull(url, "URL");
118         ensureValidState();
119         synchronized (this) {
120             return this.entries.get(url);
121         }
122     }
123 
124     @Override
125     public void removeEntry(final String url) throws IOException {
126         Args.notNull(url, "URL");
127         ensureValidState();
128         synchronized (this) {
129             // Cannot deallocate the associated resources immediately as the
130             // cache entry may still be in use
131             this.entries.remove(url);
132         }
133     }
134 
135     @Override
136     public void updateEntry(
137             final String url,
138             final HttpCacheUpdateCallback callback) throws IOException {
139         Args.notNull(url, "URL");
140         Args.notNull(callback, "Callback");
141         ensureValidState();
142         synchronized (this) {
143             final HttpCacheEntry existing = this.entries.get(url);
144             final HttpCacheEntry updated = callback.update(existing);
145             this.entries.put(url, updated);
146             if (existing != updated) {
147                 keepResourceReference(updated);
148             }
149         }
150     }
151 
152     public void cleanResources() {
153         if (this.active.get()) {
154             ResourceReference ref;
155             while ((ref = (ResourceReference) this.morque.poll()) != null) {
156                 synchronized (this) {
157                     this.resources.remove(ref);
158                 }
159                 ref.getResource().dispose();
160             }
161         }
162     }
163 
164     public void shutdown() {
165         if (this.active.compareAndSet(true, false)) {
166             synchronized (this) {
167                 this.entries.clear();
168                 for (final ResourceReference ref: this.resources) {
169                     ref.getResource().dispose();
170                 }
171                 this.resources.clear();
172                 while (this.morque.poll() != null) {
173                 }
174             }
175         }
176     }
177 
178     @Override
179     public void close() {
180         if (this.active.compareAndSet(true, false)) {
181             synchronized (this) {
182                 ResourceReference ref;
183                 while ((ref = (ResourceReference) this.morque.poll()) != null) {
184                     this.resources.remove(ref);
185                     ref.getResource().dispose();
186                 }
187             }
188         }
189     }
190 
191 }