开发者

Is there any compile-time mechanism in Java to attempt to ensure that use of a particular class is always synchronized?

开发者 https://www.devze.com 2023-04-13 00:02 出处:网络
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:

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 anyo开发者_运维技巧ne 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.

A typical bug matching this bug pattern is forgetting to synchronize one of the methods in a class that is intended to be thread-safe.

You can select the nodes labeled "Unsynchronized access" to show the code locations where the detector believed that a field was accessed without synchronization.

Note that there are various sources of inaccuracy in this detector; for example, the detector cannot statically detect all situations in which a lock is held. Also, even when the detector is accurate in distinguishing locked vs. unlocked accesses, the code in question may still be correct.

If that isn't sufficient, you can always annotate with net.jcip.annotations.NotThreadSafe which findbugs recognizes.

From Chapter 10. Annotations :

FindBugs also supports the following annotations:

  • ...
  • net.jcip.annotations.NotThreadSafe


If you want the check to be at compile time, FindBugs and PMD won't do. I would suggest Java's Annotation Processing Tool (APT). It will let you create a custom annotation processor that can add checks to the compilation process for uses of your annotated classes and cause compiler warnings or errors if your synchronization requirements are not met. In fact, you could even use it tamper with the code to add the synchronization during the compilation if it isn't already there.

To use the annotation processor you create, you just need to make sure it's on the classpath when you compile your project. No extra automated analysis needed.


If you call notify() without a synchronized block around it or the method being synchronized you will get an IllegalMonitorStateExcept (see the documentation). However, doing it is very hacky and should, if at all, only be used for debugging and not in a production setting.


At runtime you may use Thread.holdsLock().

Have you thought about inheriting from Foo, like SynchronizedFoo and using that in your code while others may still use Foo as needed?

0

精彩评论

暂无评论...
验证码 换一张
取 消