In a Java ZK application, in ViewModel, I have multiple threads executing a particular function. The first time that function is executed by any thread it takes a long time but after it has been executed once, it returns immediately when executed by the other threads, as it has values retrieved in cache by then. But it should be executed by just one thread the first time, as if multiple threads execute that function, it will not return to any of them as cache remains empty when each of them calls the same functions and as a result, returning time adds up for all of them. So how can I make other threads wait for the first thread to complete as the threads belong to different objects and thus synchronizing the method will not work here. Can a variable be used here which can communicate to the other threads that the first thread has completed? Please note that all the threads belong to different objects of the same class i.e a ViewModel and it cannot extend the thread class or implement Runnable as it is a ZK framework class. Any solution can be suggested.
something like this:
static Object lock;
...
if (objectYouAreHopingHasBeenCached == null) {
synchronized (lock) {
if (objectYouAreHopingHasBeenCached == null) {
// fetch the object, put in in objectYouAreHopingHasBeenCached
}
}
}
return objectYouAreHopingHasBeenCached;