java - HashMap is broken/ performance issues -
java - HashMap is broken/ performance issues -
currently have hashmap implemented
private static map<string, item> cached = new hashmap<string, item>(); and item object properties date expirationtime , , byte[] data
this map used when multiple threads concurrently start hitting this. check
1.
class="lang-java prettyprint-override">public static final byte[] getcacheddata(httpservletrequest request) throws servletexception { string url = getfullurl(request); map<string, item> cache = getcache(request); // chec item item = null; synchronized (cache) { item = cache.get(url); if (null == item) homecoming null; // create sure not on hr old. if (item.expirationtime.gettime() < system.currenttimemillis()) { cache.remove(url); item = null; } } if (null == item) { log.info("expiring item: " + url); homecoming null; } homecoming item.data; } 2. if info returned null, create , info , cache in hashmap
class="lang-java prettyprint-override">public static void cachedatax(httpservletrequest request, byte[] data, integer minutes) throws servletexception { item item = new item(data); string url = getfullurl(request); map<string, item> cache = getcache(request); log.info("caching item: " + url + " - bytes: " + data.length); synchronized (cache) { calendar cal = calendar.getinstance(); cal.add(calendar.minute, minutes); item.expirationtime = cal.gettime(); cache.put(url, item); } } seems if multiple threads access key (url in case) , info gets added cache more 1 time @ same key location [ getcachedata homecoming null multiple threads since hashmap has not finished writing info first thread ]
any suggestions how solve issue ?
in cachedatax add together check existence of item before add together (inside of synchronized block).
synchronized (cache) { if (cache.get(url) == null) { calendar cal = calendar.getinstance(); cal.add(calendar.minute, minutes); item.expirationtime = cal.gettime(); cache.put(url, item); } } this ensure multiple threads have done lookup , returned null cannot add together same info cache. 1 add together , others threads silently ignore since cache has been updated.
java performance hashmap concurrenthashmap
Comments
Post a Comment