View Javadoc

1   /*
2    *  This file is part of the Heritrix web crawler (crawler.archive.org).
3    *
4    *  Licensed to the Internet Archive (IA) by one or more individual 
5    *  contributors. 
6    *
7    *  The IA licenses this file to You under the Apache License, Version 2.0
8    *  (the "License"); you may not use this file except in compliance with
9    *  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, software
14   *  distributed under the License is distributed on an "AS IS" BASIS,
15   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   *  See the License for the specific language governing permissions and
17   *  limitations under the License.
18   */
19   
20  package org.archive.util;
21  
22  import java.util.Set;
23  import java.util.concurrent.ConcurrentHashMap;
24  
25  /***
26   * Trivial all-in-memory object cache, using a single internal
27   * ConcurrentHashMap.
28   * 
29   * @contributor gojomo
30   * @param <V>
31   */
32  public class ObjectIdentityMemCache<V> 
33  implements ObjectIdentityCache<String,V> {
34      ConcurrentHashMap<String, V> map; 
35      
36      public ObjectIdentityMemCache() {
37          map = new ConcurrentHashMap<String, V>();
38      }
39      
40      public ObjectIdentityMemCache(int cap, float load, int conc) {
41          map = new ConcurrentHashMap<String, V>(cap, load, conc);
42      }
43  
44      public void close() {
45          // do nothing
46      }
47  
48      public V get(String key) {
49          return map.get(key); 
50      }
51  
52      public V getOrUse(String key, Supplier<V> supplierOrNull) {
53          V val = map.get(key); 
54          if (val==null && supplierOrNull!=null) {
55              val = supplierOrNull.get(); 
56              V prevVal = map.putIfAbsent(key, val);
57              if(prevVal!=null) {
58                  val = prevVal; 
59              }
60          }
61          return val; 
62      }
63  
64      public int size() {
65          return map.size();
66      }
67  
68      public Set<String> keySet() {
69          return map.keySet();
70      }
71  
72      public void sync() {
73          // do nothing
74      }
75  }