I have Cached List, my code looks like this
public class MyList {
private final List<String> cache = new ArrayList<String>();
private List<String> loadMyList() {
// HEAVY OPERATION TO LOAD DATA
}
public List<String> list() {
synchronized (cache) {
if( cache.size() == 0 ) {
cache.addAll(loadMyList());
}
return Collections.unmodifiableList(cache);
}
}
public void invalidateCache() {
synchronized (cache) {
cache.clear();
}
}
}
Because list load is very heavy I got a request that if list load is currently in progress i return "old" cached data...
Is that possible, and can someone give me pointers on how to proceed from here
EDIT : Adam Horvath And bayou.io sugested something like this
public class MyList
{
private final List<String> cache = new ArrayList<String>();
private final List<String> oldCache = new ArrayList<String>();
private volatile boolean loadInProgress = false;
private List<String> loadMyList()
{
// HEAVY OPERATION TO LOAD DATA
}
public List<String> list()
{
synchronized (cache)
{
if( loadInProgress )
return Collections.unmodifiableList( oldCache );
else
return Collections.unmodifiableList(cache);
}
}
public void invalidateCache()
{
synchronized (cache)
{
// copy to old cache
oldCache = new ArrayList<String>( cache );
// set flag that load is in progress
loadInProgress = true;
// clear cache
cache.clear();
// initialize load in new thread
Thread t = new Thread(new Runnable()
{
public void run()
{
cache.addAll( loadMyList() );
// set flag that load is finished
loadInProgress = false;
}
});
t.start();
}
}
}
Will this edited code have any issues?? Since I am not experienced in multithreading and/or cashing optimisation i would appreciate any and all performance suggestion
list()
get a view on your list - that means that when you clear / repopulate the list, callers that still have a copy of that view could see the list in an unstable state. Are you sure you want that? Also there is no "old" data in your example - either the list is empty or it's got something but once it is loaded it is not updated again... – Carbohydrate