Add wso2bpel-ext code
[vfc/nfvo/wfengine.git] / wso2bpel-ext / wso2bpel-core / wso2bpel-mgr / src / main / java / org / openo / carbon / bpel / util / LRULinkedHashMap.java
1 /**
2  * Copyright 2016 [ZTE] and others.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.openo.carbon.bpel.util;
17
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.LinkedHashMap;
21 import java.util.Map;
22 import java.util.concurrent.locks.Lock;
23 import java.util.concurrent.locks.ReentrantLock;
24
25 /**
26  * 
27  * @author bsli
28  * 
29  * @param <K>
30  * @param <V>
31  */
32 @SuppressWarnings("serial")
33 public class LRULinkedHashMap<K, V> extends LinkedHashMap<K, V> {
34   private final int maxCapacity;
35
36   private static final float DEFAULT_LOAD_FACTOR = 0.75f;
37
38   private final Lock lock = new ReentrantLock();
39
40   public LRULinkedHashMap(int maxCapacity) {
41     super(maxCapacity, DEFAULT_LOAD_FACTOR, true);
42     this.maxCapacity = maxCapacity;
43   }
44
45   @Override
46   protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
47     return size() > maxCapacity;
48   }
49
50   @Override
51   public boolean containsKey(Object key) {
52     try {
53       lock.lock();
54       return super.containsKey(key);
55     } finally {
56       lock.unlock();
57     }
58   }
59
60   @Override
61   public V get(Object key) {
62     try {
63       lock.lock();
64       return super.get(key);
65     } finally {
66       lock.unlock();
67     }
68   }
69
70   @Override
71   public V put(K key, V value) {
72     try {
73       lock.lock();
74       return super.put(key, value);
75     } finally {
76       lock.unlock();
77     }
78   }
79
80   public int size() {
81     try {
82       lock.lock();
83       return super.size();
84     } finally {
85       lock.unlock();
86     }
87   }
88
89   public void clear() {
90     try {
91       lock.lock();
92       super.clear();
93     } finally {
94       lock.unlock();
95     }
96   }
97
98   public Collection<Map.Entry<K, V>> getAll() {
99     try {
100       lock.lock();
101       return new ArrayList<Map.Entry<K, V>>(super.entrySet());
102     } finally {
103       lock.unlock();
104     }
105   }
106 }