Learning records when using LinkedHashMap

Source: Internet
Author: User

LRU Algorithm

LRU (Least Recently Used), minimum algorithm Used Recently
Eliminate the rows that have been visited at least in the recent period.
Therefore, you need to set a counter for each row. The LRU algorithm clears the counters of hit rows and Adds 1 to the counters of other rows.
When a replacement is required, the data row with the largest counter value is eliminated.
This is an efficient and scientific algorithm, and its Counter clearing process can eliminate unnecessary data that is frequently called from the Cache,
Improves the Cache utilization.

LinkedHashMap in Java
This implementation differs from HashMap in that the latter maintains a list of dual links running on all entries.
The Link List defines the iteration order, which is usually the order in which keys are inserted into the ing (insertion order ).

Difference between LinkedHashMap and TreeMap
The first two are map, so there is no difference in the key value. The difference is that when Iterator is used to traverse
LinkedHashMap stores the insert sequence of records, first inserts and first traverses
TreeMap is sorted in ascending order by default. You can also specify a comparator for sorting. In ascending order.

Override the removeEldestEntry (Map. Entry) method to implement the policy.
The old ing is automatically removed.

The hash ing of the link has two parameters that affect its performance: initial capacity and loading factor. Select for initial capacity
A very high value has less impact on this type than HashMap, because the iteration time of this type is not affected by the capacity.

The LRU algorithm is implemented using LinkedHashMap, which is mainly to override boolean removeEldestEntry (Map. Entry <K, V> eldest)
Method.
If the oldest entry should be removed from the ing, true is returned. If the retained entry is returned, false is returned.

Override the removeEldestEntry (Map. Entry) method to implement the policy, so that the old ing is automatically removed when the new ing is added to the ing.
This method can be used to remove the oldest entry every time a new entry is added. This method is useful if ing indicates Caching:
It allows ing to reduce memory consumption by deleting old entries.

public class LRULinkedHashMap<K, V> extends LinkedHashMap<K, V> {private static final long serialVersionUID = 2490814505277321242L;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;}@Overrideprotected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {return size() > maxCapacity;}@Overridepublic V get(Object key) {try {lock.lock();return super.get(key);}finally {lock.unlock();}}public V put(K key, V value) {try {lock.lock();return super.put(key, value);} finally {lock.unlock();}};}

In the cache system, the implemented algorithms are as follows (common)
Cahce algorithm cache algorithm or replacement algorithm:

1. The Least Recently Used algorithm Least Recently Used (LRU ):
The most intuitive structure should be List. The algorithm adopted is: each time an element is accessed, this element is placed at the end of the List, so that the farthest used
The element is naturally placed on the other end of the List. Each evict operation removes the farthest element used. But the data that is often used in reality
The structure is HashMap + List. Because List is too slow, List can only provide the O (n) algorithm, so the add, remove, and get algorithms must be O (1)
You must use HashMap. The simplest implementation is to use the built-in javashashmap of JDK. You can think of it as a normal HashMap,
The keys of each element are connected by a linked list to achieve sequential structure. The default element sequence of LinkedHashMap is put,
If a constructor with parameters is used, LinkedHashMap adjusts the internal order according to the access order. Except for the get () method of LinkedHashMap
In addition to the returned elements, you can also place the accessed elements at the bottom of the linked list. In this way, each element at the top is the removed element.

2. First In, First Out Algorithm
This is more intuitive, It is a Queue. However, to ensure O (1) efficiency, we still need to use LinkedHashMap. But this time the default none is used
Parameter constructor. The put sequence is used inside the LinkedHashMap. Therefore, you can remove the top point each time.

3. Least Frequently Used (LFU)
The core of this algorithm is that the number of times attribute of this element is added to 1 each time an element is accessed. Therefore, each remove operation is the least frequently used attribute.
Element. We cannot implement it using LinkedHashMap this time, because LinkedHashMap does not accept the comparator Parameter Function. Some programs
Is implemented by using tranquility list + HashMap. In this way, the add and get operations are still O (1), but the remove operations must be sorted first and then removed,
The fastest is O (n * log n), for example, using quick sorting. Or simply, when removing, you just need to do an algorithm to find the smallest element to remove access.
Element with the smallest number of times.

[Note], some content comes from: http://blog.csdn.net/michaellufhl/article/details/6203666

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.