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   *
53   * This {@link HttpCacheStorage} implementation is intended for use with {@link FileResource}
54   * and similar.
55   *
56   * @since 4.1
57   */
58  @ThreadSafe
59  public class ManagedHttpCacheStorage implements HttpCacheStorage, Closeable {
60  
61      private final CacheMap entries;
62      private final ReferenceQueue<HttpCacheEntry> morque;
63      private final Set<ResourceReference> resources;
64      private final AtomicBoolean active;
65  
66      public ManagedHttpCacheStorage(final CacheConfig config) {
67          super();
68          this.entries = new CacheMap(config.getMaxCacheEntries());
69          this.morque = new ReferenceQueue<HttpCacheEntry>();
70          this.resources = new HashSet<ResourceReference>();
71          this.active = new AtomicBoolean(true);
72      }
73  
74      private void ensureValidState() throws IllegalStateException {
75          if (!this.active.get()) {
76              throw new IllegalStateException("Cache has been shut down");
77          }
78      }
79  
80      private void keepResourceReference(final HttpCacheEntry entry) {
81          final Resource resource = entry.getResource();
82          if (resource != null) {
83              // Must deallocate the resource when the entry is no longer in used
84              final ResourceReference ref = new ResourceReference(entry, this.morque);
85              this.resources.add(ref);
86          }
87      }
88  
89      public void putEntry(final String url, final HttpCacheEntry entry) throws IOException {
90          Args.notNull(url, "URL");
91          Args.notNull(entry, "Cache entry");
92          ensureValidState();
93          synchronized (this) {
94              this.entries.put(url, entry);
95              keepResourceReference(entry);
96          }
97      }
98  
99      public HttpCacheEntry getEntry(final String url) throws IOException {
100         Args.notNull(url, "URL");
101         ensureValidState();
102         synchronized (this) {
103             return this.entries.get(url);
104         }
105     }
106 
107     public void removeEntry(final String url) throws IOException {
108         Args.notNull(url, "URL");
109         ensureValidState();
110         synchronized (this) {
111             // Cannot deallocate the associated resources immediately as the
112             // cache entry may still be in use
113             this.entries.remove(url);
114         }
115     }
116 
117     public void updateEntry(
118             final String url,
119             final HttpCacheUpdateCallback callback) throws IOException {
120         Args.notNull(url, "URL");
121         Args.notNull(callback, "Callback");
122         ensureValidState();
123         synchronized (this) {
124             final HttpCacheEntry existing = this.entries.get(url);
125             final HttpCacheEntry updated = callback.update(existing);
126             this.entries.put(url, updated);
127             if (existing != updated) {
128                 keepResourceReference(updated);
129             }
130         }
131     }
132 
133     public void cleanResources() {
134         if (this.active.get()) {
135             ResourceReference ref;
136             while ((ref = (ResourceReference) this.morque.poll()) != null) {
137                 synchronized (this) {
138                     this.resources.remove(ref);
139                 }
140                 ref.getResource().dispose();
141             }
142         }
143     }
144 
145     public void shutdown() {
146         if (this.active.compareAndSet(true, false)) {
147             synchronized (this) {
148                 this.entries.clear();
149                 for (final ResourceReference ref: this.resources) {
150                     ref.getResource().dispose();
151                 }
152                 this.resources.clear();
153                 while (this.morque.poll() != null) {
154                 }
155             }
156         }
157     }
158 
159     public void close() {
160         shutdown();
161     }
162 
163 }