Can I change my code from:
class Sample{
private Object _lock=new Object();
public void someMethod(){
synchronized(_lock){
doSomething();
}
}
}
to:
class Sample{
private ISchedulingRule _lock=new SomeSchedulingRule();
public void someMethod(){
try{
Job.getManager().beginRule(_lock);
doSomething();
}finally{
Job.getManager().endRule(_lock);
}
}
}
I’m reading “java concurrency in practice”, and they say if I wanna use some explicit lock, I have to guarantee the memory visibility.
So the question is:
If I can guarantee the memory visibility, can I use the code at bottom to replace the code at top(replace intrinsic synchronization with eclipse IJobManager.beginRule and IJobManager.endRule)
If your only goal is to achieve synchronization then the answer is yes.
That said, there are some (hidden) gotchas that you need to be aware of. Since
JobManageris designed to prevent dead-locks to some extent, then there are somewhat strict rules for using and defining nested rules (a limitation that Java synchronized blocks don’t have). There is no public API for checking whether a thread is holding a rule/lock or not. Also,beginRulecannot be canceled by calling interrupt on waiting thread. To name a few.