基本概念:https://www.cnblogs.com/xiaoxi/p/6170590.html

遇到问题:

 

1、构造方法

public static LinkedHashMap<String,Long> lhm= new LinkedHashMap<String,Long>(16, 0.75f, true);  //一定要加true,不然不会按照访问顺序排序。

 

2、访问方式

使用get(Object o)方式会改变该KEY值访问顺序,必须使用如下方法访问:

LinkedHashMap<String,Long> lhm = new LinkedHashMap<String,Long>(16, 0.75f, true);
Set<Map.Entry<String, Long>> set = lhm.entrySet();
Iterator<Map.Entry<String, Long>> iterator = set.iterator();
synchronized (iterator) {
while (iterator.hasNext())
{
Entry<String, Long> entry = iterator.next();
long vintime = entry.getValue();
System.out.print(vintime+" ");
}
}

3、该数据结构非线程安全,多线程使用必须加锁

1) get()

2) put()

3) 遍历

 

import java.util.LinkedHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LRULinkedHashMap<K, V> extends LinkedHashMap<K, V> {
/**
*
*/
private static final long serialVersionUID = -952299094512767664L;
private final int maxCapacity;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
private final Lock lock = new ReentrantLock();

public LRULinkedHashMap(int maxCapacity) {
super(maxCapacity, DEFAULT_LOAD_FACTOR, true);
this.maxCapacity = maxCapacity;
}

@Override
protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
return size() > maxCapacity;
}

@Override
public V get(Object key) {
try {
lock.lock();
return super.get(key);
} finally {
lock.unlock();
}
}
//可以根据实际情况,考虑对不同的操作加锁
@Override
public V put(K key, V value) {
try {
lock.lock();
return super.put(key, value);
} finally {
lock.unlock();
}
}

}

 

相关文章:

  • 2021-07-15
  • 2021-05-02
  • 2022-01-08
  • 2021-09-27
  • 2021-09-01
  • 2021-12-13
  • 2021-07-12
  • 2021-12-04
猜你喜欢
  • 2022-01-14
  • 2021-12-01
  • 2021-12-03
  • 2021-11-30
  • 2021-12-19
  • 2021-11-19
相关资源
相似解决方案