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