Given is the following pseudo code. A function may be entered by multiple threads simultaneously. I want all threads to execute a()
and c()
, but b()
must only be executed by those threads that were not locked when entering the synchronized block.
In other words: If a thread must wait for the lock, then I want it to wait until the lock is released and then jump over b()
and continue with c()
right away.
public void code() {
a() // check if page is present locally
if (pageMissing) {
synchronized (this) {
page = b(); // get page over REST
}
}
c() // access page
}
How is this useful? Imagine b()
calls an external REST function to update local data. When a thread enters, we want to be sure that the function is called and local data is updated, but once the blocking thread exits b()
we know local data is current and we don't want to waste resources in having consecutive threads that were already waiting call the update function again.