We have a class in our codebase currently that uses the synchronized keyword at the method level to ensure data consistency in multithreaded operations. It looks something like this:
public class Foo
{
public synchronized void abc() { ... }
public synchronized void def() { ... }
//etc.
}
The nice thing about this is that anyone using the class gets the synchronization for free. When you create an instance of Foo, you don’t have to remember to access it inside of a synchronized block or anything like that.
Unfortunately, it seems that synchronization at the method level isn’t going to cut it anymore. Instead we’re going to have to start synchronizing on Foo itself. I don’t think anything like java.util.concurrent.AtomicReference is going to cut it either. I want to make sure no one else touches an instance of Foo while a particular (and possibly somewhat lengthy) operation is going on. So now we’re going to have blocks like this 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 a few developers and I share this code. Foo objects are fairly ubiquitous. Since we’re not getting the synchronization for free any more at the method level, we must ALWAYS remember to access a Foo object within a synchronized block.
So my question is, is there any mechanism (built-in or third party) in Java to allow me to generate warnings or errors at compile-time if an instance of Foo is accessed outside of a synchronized block?
Ideally it would be something I can either do to the class declaration (made up example below):
@EnsureSynchronized
public class Foo
{
//etc.
}
Or something I could do when I declare instances of Foo (made up example below):
@EnsureSynchronized
private Foo foo;
I know if I really wanted to I could probably write a custom FindBugs or PMD rule to do this, but I was hoping something like this 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 accessed and modified inside synchronized blocks?
Findbugs is pretty good at finding inconsistent synchronization so as long as you have some code that synchronizes all accesses to an object, and run findbugs, it should alert you to failures to sync.
If that isn’t sufficient, you can always annotate with
net.jcip.annotations.NotThreadSafewhich findbugs recognizes.From Chapter 10. Annotations :