Our code base now has a class that uses the synchronized at the method level to ensure data consistency in multi-threaded operations. It looks something like this:
public class Foo { public synchronized void abc() { ... } public synchronized void def() { ... }
The best part is that anyone who uses the class gets synchronization for free. When you create an instance of Foo , you donβt need to remember access to it inside a synchronized block or something like that.
Unfortunately, it seems that synchronization at the method level will no longer shorten it. Instead, we need to start synchronization on Foo . I do not think that something like java.util.concurrent.AtomicReference will cut back either. I want to make sure that no one touches the Foo instance while the specific (and possibly somewhat lengthy) operation is in progress. So, now we will have such blocks in the code:
Foo foo = new Foo(); //this got created somewhere //somewhere else entirely synchronized(foo) { //do operation on foo foo.doStuff(); foo.doOtherStuff(); }
So the main thing I'm worried about is that several developers and I share this code. Foo objects are pretty ubiquitous. Since we no longer get synchronization at the method level, we should ALWAYS remember access to the Foo object in the synchronized block.
So my question is: is there any mechanism (built-in or third-party) in Java so that I can generate warnings or errors at compile time if the Foo instance is accessed outside the synchronized block
Ideally, this would be something that I can either do with the class declaration (example below):
@EnsureSynchronized public class Foo {
Or something that I could do when I declare Foo instances (the example below):
@EnsureSynchronized private Foo foo;
I know if I really wanted to be able to write my own FindBugs or PMD rule for this, but I was hoping something similar already existed.
So, I ask you, SO community, if you were in this situation, how would you try to ensure that Foo objects are only ever accessible and changed inside synchronized blocks?