Collections Trick I: LRU Cache

Maybe it's just my job. Or maybe it's just fashion. The fact is that I meet little people understanding and/or taking advantage of Data Structures and Algorithms. People tend to use higher-level abstractions (EJBs, JSPs and the like) and usually forget about the low-level stuff.

I don't mean you have to be an expert on that, but I think it's indeed useful.

So the other day, talking to a customer, I noticed he was trying to build a LRU (least recently used) cache for whatever it was. And he was in trouble. He didn't know that's already done, and it's well done.

The fact is that he didn't pay attention to the LinkedHashMap. You do it as follows:


LinkedHashMap lruCache = new LinkedHashMap( 10, 0.75f, true )
 {
    protected boolean removeEldestEntry( java.util.Map.Entry entry )
      {
        return size() > 100;
      }
 };

So I think it's a good idea to post these tricks from time to time, so everybody can take advantage of them.

Have a good hacking!

Comentarios:

Enviar un comentario:
Los comentarios han sido deshabilitados.
About

swinger

Search

Archives
« julio 2014
lunmarmiéjueviesábdom
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
   
       
Hoy