[ Marko Medojević @ 07.12.2010. 21:36 ] @
Ćao. Pokušavam da napravim prostu cache klasu za Android koja će mi omogućiti keširanje bez opasnosti da uletim u out of memory. Napisao sam nešto ovako: Code: import java.lang.ref.SoftReference; import java.util.HashMap; import java.util.Map; public class MemoryCache { // singleton implemtation private static MemoryCache instance = null; private MemoryCache() { } public static MemoryCache getInstance() { if(instance == null) { instance = new MemoryCache(); } return instance; } // private Map<String, SoftReference<Object>> cachedItems = new HashMap<String, SoftReference<Object>>(); public void saveCacheItem(String itemId, Object objForCache) { cachedItems.put(itemId, new SoftReference<Object>(objForCache)); } public Object getCacheItem(String itemId) { if(cacheItemExists(itemId)) { return cachedItems.get(itemId).get(); } else { return null; } } public Boolean cacheItemExists(String itemId) { if(cachedItems.containsKey(itemId)) { if(cachedItems.get(itemId) != null ) { return true; } } return false; } public void deleteCacheItem(String itemId) { if(cachedItems.containsKey(itemId)) { cachedItems.remove(itemId); } } } Međutim, dešava se sledeće. Iako je u pitanju objekat od svega nekoliko polja sa geterima i seterima, on biva jako brzo GC-ovan. Koliko sam razumeo SoftReference bi trebale da odlažu brisanje objekata iz memorije sve dok ne preti out of memory. Tesitiranje sam izvršio na Android emulatori, pa ne znam da li u tome može biti problem ili možda radim nešto pogrešno. |