Java中是否有任何编译时机制试图确保始终同步特定类的使用?

时间:2022-07-01 07:07:57

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:

我们的代码库中有一个类,它在方法级别使用synchronized关键字来确保多线程操作中的数据一致性。它看起来像这样:

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.

关于这一点的好处是任何使用该类的人都可以免费获得同步。当您创建Foo实例时,您不必记住在同步块或类似内容中访问它。

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本身。我认为像java.util.concurrent.AtomicReference这样的东西也不会削减它。我想确保没有其他人触及Foo的实例,而特定的(可能有些冗长的)操作正在进行。所以现在我们将在代码中使用这样的块:

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.

所以我担心的主要是一些开发人员和我分享这些代码。 Foo对象相当普遍。由于我们不再在方法级别获得免费同步,因此我们必须始终记住访问同步块中的Foo对象。

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?

所以我的问题是,在Java中是否有任何机制(内置或第三方)允许我在编译时生成警告或错误,如果在同步块之外访问Foo的实例?

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):

或者当我声明Foo的实例时我可以做的事情(下面的例子):

@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.

我知道如果我真的想要我可以写一个自定义的FindBugs或PMD规则来做到这一点,但我希望这样的事情已经存在。

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?

所以我问你,SO社区,如果你处于这种情况,你将如何确保只在同步块中访问和修改Foo对象?

4 个解决方案

#1


6  

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.

Findbugs非常擅长发现不一致的同步,因此只要你有一些代码可以同步对象的所有访问,并运行findbugs,它就会提醒你同步失败。

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.

如果这还不够,您可以随时使用findbugs识别的net.jcip.annotations.NotThreadSafe进行注释。

From Chapter 10. Annotations :

从第10章开始。注释:

FindBugs also supports the following annotations:

FindBugs还支持以下注释:

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

#2


1  

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.

如果您希望检查在编译时,FindBugs和PMD将不会这样做。我建议使用Java的注释处理工具(APT)。它将允许您创建自定义注释处理器,该处理器可以对编译过程添加检查以使用带注释的类,并在不满足同步要求时导致编译器警告或错误。事实上,你甚至可以使用它来篡改代码,以便在编译期间添加同步(如果它还没有)。

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.

要使用您创建的注释处理器,只需在编译项目时确保它在类路径上。无需额外的自动分析。

#3


0  

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.

如果您调用notify()而没有围绕它的同步块或正在同步的方法,您将获得IllegalMonitorStateExcept(请参阅文档)。但是,这样做非常hacky,如果有的话,应该仅用于调试而不是用于生产设置。

#4


0  

At runtime you may use Thread.holdsLock().

在运行时,您可以使用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?

您是否考虑过从Foo继承,如SynchronizedFoo并在您的代码中使用它,而其他人可能仍然根据需要使用Foo?

#1


6  

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.

Findbugs非常擅长发现不一致的同步,因此只要你有一些代码可以同步对象的所有访问,并运行findbugs,它就会提醒你同步失败。

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.

如果这还不够,您可以随时使用findbugs识别的net.jcip.annotations.NotThreadSafe进行注释。

From Chapter 10. Annotations :

从第10章开始。注释:

FindBugs also supports the following annotations:

FindBugs还支持以下注释:

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

#2


1  

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.

如果您希望检查在编译时,FindBugs和PMD将不会这样做。我建议使用Java的注释处理工具(APT)。它将允许您创建自定义注释处理器,该处理器可以对编译过程添加检查以使用带注释的类,并在不满足同步要求时导致编译器警告或错误。事实上,你甚至可以使用它来篡改代码,以便在编译期间添加同步(如果它还没有)。

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.

要使用您创建的注释处理器,只需在编译项目时确保它在类路径上。无需额外的自动分析。

#3


0  

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.

如果您调用notify()而没有围绕它的同步块或正在同步的方法,您将获得IllegalMonitorStateExcept(请参阅文档)。但是,这样做非常hacky,如果有的话,应该仅用于调试而不是用于生产设置。

#4


0  

At runtime you may use Thread.holdsLock().

在运行时,您可以使用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?

您是否考虑过从Foo继承,如SynchronizedFoo并在您的代码中使用它,而其他人可能仍然根据需要使用Foo?