Spring和部分方法的同步

发布于 2024-09-14 17:38:23 字数 276 浏览 1 评论 0原文

我有一个作为Spring有线bean的经理。我相信默认情况下为 spring 定义的每个 bean 都是作为单例连接的。我在这个 bean 中有一些需要同步的方法。 那我该怎么做——

void zzz() {
 synchronized (this) {
   ...
 }
}

或者

void zzz() {
 synchronized (MyClass.class) {
   ...
 }
}

I have a manager as Spring wired bean. I believe every bean defined for spring by default is wired as singleton. I have some methods in this bean which I need to synchronize.
How should I be doing that then --

void zzz() {
 synchronized (this) {
   ...
 }
}

or

void zzz() {
 synchronized (MyClass.class) {
   ...
 }
}

?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怪异←思 2024-09-21 17:38:23

两者的主要区别在于,第一种情况是使用类的实例作为监视器,而第二种情况是使用类的实例作为监视器。

第一个可能是您的情况的选择,因为在不久的将来,如果您决定拥有多个类实例,它们的方法将在各自的实例上同步。与使用类作为监视器相反,如果一个线程在一个实例上调用同步方法,则其他线程将无法在同一类的任何实例上调用方法(同步的方法)。

The main difference in the two is that in the first case, the the instance of the class as the monitor and the second one uses the Class as the monitor.

The first one is probably the way to go in your case because, in the near future if you decide to have many instances of your class, their methods will be synchronized on the respective instances. As opposed to if you use a Class as a monitor, if one thread is calling a synchronized method on one instance, no other threads will be able to call methods (those that are synchronized) on any instances of the same class.

早茶月光 2024-09-21 17:38:23

除非您要访问可变的静态类变量(一开始可能会很麻烦),否则第一个是适当的同步方法。

了解虽然 Spring 仅创建单例 bean 的一个实例并将其用于任何依赖于该类型 bean 的人,但单例不是静态实体。没有编译器约束阻止您在 Spring 上下文之外自己实例化该类。这只是唯一的实例,因为 Spring 知道不要创建更多的实例......而不是因为它无法完成。我在这里想要指出的一点是,在类级数据和单例数据之间进行比较是不确定的,甚至是不正确的。

因此,同步应该发生在尽可能小的范围内。在您的情况下,这意味着在包含共享数据的对象实例上进行同步,而不是在整个类的更广泛范围内进行同步。

Unless you're accessing mutable static class variables (potentially nasty to begin with), the first is the appropriate way to synchronize.

Understand that while Spring is only creating one instance of a singleton bean and using it for anybody who has a dependency on a bean of that type, the singleton is not a static entity. There is no compiler constraint preventing you from instantiating that class yourself outside the Spring context. It's simply the only instance because Spring knows not to make more of them... not because it can't be done. The point I'm trying to make here is that it's iffy bordering on incorrect to draw a parallel between class-level data and the singleton's data.

In corollary, synchronization should occur on the narrowest scope possible. In your case, that means synchronize on the object instance containing the shared data rather than on the wider scope of the entire class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文