I have the following structure:
public void someMethod(){
//DO SOME STUFF
try{
doSomeProcessing();
}
catch (Exception e){
loadSomeHeavyData();
doSomeProcessing();
}
}
The method someMethod may be called concurrently by many threads. The doSomeProcessing may throw an exception (it is using some data in the backend that could become obsolete).
If an exception is thrown then loadSomeHeavyData(); does some timeconsuming task that let’s say “updates” all the current data and I am able to call doSomeProcessing();.
Problem: How can I make sure that loadSomeHeavyData(); is called only once? If I put some atomic flag in the entry of loadSomeHeavyData(); then I can not be sure when this should be cleared.
How can I solve this? Just a note: I can not modify doSomeProcessing(); as it is an external API and I am using decorator pattern to use it.
Your
loadSomeHeavyDatamethod could use a blocking mechanism to make all threads wait until it has finished its update, but only let one of them actually do the update:Note my assumptions:
doSomeProcessinga second time with updated dataloadSomeHeavyDataonce, ever – if not you will need to reset the flag and the CountdownLatch (which would then probably not be the most appropriate mechanism).EDIT
Your latest comment indicates that you actually want to call
loadSomeHeavyDatamore than once, just not more than once at a time.