开发者

caching in java

开发者 https://www.devze.com 2023-02-07 04:24 出处:网络
guys I am implementing a simple example of 2 level cache in java: 1st level is memeory 2nd - filesystem I am new in java and I do this just for understanding caching in java.

guys I am implementing a simple example of 2 level cache in java: 1st level is memeory 2nd - filesystem

I am new in java and I do this just for understanding caching in java. And sorry for my English, this language is not native for me :)

I have completed 1st level by using LinkedHashMap class and removeEldestEntry method and it is looks like this:

import java.util.*;

public class level1 {
private static final int max_cache = 50;
private Map cache = new LinkedHashMap(max_cache, .75F, true) {
    protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() > max_cache;
    }
};


public level1() {
    for (int i = 1; i < 52; i++) {
        String string = String.valueOf(i);
        cache.put(string, string);

        System.out.println("\rCache size = " + cache.size() +
                           "\tRecent value = " + i +
                           " \tLast value = " +
                           cache.get(string) + "\tValues in cache=" +
                           cache.values());

    }

}

Now, I am going to code my 2nd level. What 开发者_开发技巧code, methods I should write to implement this tasks:

1) When the 1st level cache is full, the value shouldn't be removed by removeEldestEntry but it should be moved to 2nd level (to file)

2) When the new values are added to 1st level, firstly this value should be checked in file (2nd level) and if it exists it should be moved from 2nd to 1st level.

And I tried to use LRUMap to upgrade my 1st level but the compiler couldn't find class LRUMap in library, what's the problem? Maybe special syntax needed?


You can either use the built in java serialization mechanism and just send your stuff to file by wrapping FileOutputStrem with DataOutputStream and then calling writeObjet().

This method is simple but not flexible enough. for example you will fail to read old cache from file if your classes changed.

You can use serialization to xml, e.g. JaxB or XStream. I used XStream in past and it worked just fine. You can easily store any collection in file and the restore it.

Obviously you can store stuff in DB but it is more complicated.


A remark is that you are not getting thread safety under consideration for your cache! By default LinkedHashMap is not thread-safe and you would need to synchronize your access to it. Even better you could use ConcurrentHashMap which deals with synchronization internally being able to handle by default 16 separate threads (you can increase this number via one of its constructors).

I don't know your exact requirements or how complicated you want this to be but have you looked at existing cache implementations like the ehcache library?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号