user5047085 :
Say I have a method:
public void run(){
synchronized(this.foo){
}
}
but sometimes when I run this method, I don't need to synchronize on anything.
What is a good pattern to conditionally synchronize on something? The only pattern I can think of is a callback, something like this:
public void conditionalSync(Runnable r){
if(bar){
r.run();
return;
}
synchronized(this.foo){
r.run();
}
}
public void run(){
this.conditionalSync(()->{
});
}
is there another way to do it, without a callback?
xingbin :
Instead of synchronized
keyword, maybe you can use ReentrantLock
(which is more flexible and powerful).
Example:
ReentrantLock lock = ...;
public void run(){
if (bar) {
lock.lock();
}
try {
// do something
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}