I have legacy code that has cache implementation that looks like this:
long lastUpadate;
...
public void checkCach(){
if(lastUpdated + UPDATE_INTERVAL < System.currentTimeMillis()){
synchronized(this){
//cache update goes here
lastUpdate = System.currentTimeMillis();
}
}
}
Can there be a problem in multicore processor enviroment that Threads would not see updated lastUpdate field because they check it outside of synchronized section (issue of processors core caches)?
Updated: also can reordering be applied to this synchronized block, that first lastUpdate field would be set and only then cache update would be executed
if
lastUpdateis a field variable set it tovolatile lastUpdateto force all threads trying to view its value to cross the memory barrier. Therefore you can guaranteed that whatever thread is readinglastUpdate, they will get the most recent value. Beware though, volatile cannot guarantee atomic operations.