有多少线程可以同时调用对象的非同步方法? [英] How many threads can simultaneously invoke an unsynchronized method of an object?

查看:150
本文介绍了有多少线程可以同时调用对象的非同步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以让我们假设我有一个类X的方法m。方法m是不同步,它不需要是因为它不会真正改变类型X的对象x的状态。

So let's say I have a class X with a method m. Method m is NOT synchronized and it doesn't need to be since it doesn't really change the state of the object x of type X.

在某些线程中,我调用这样的方法:xm()。所有这些线程使用相同的对象x。

In some threads I call the method like this: x.m(). All these threads use the same object x.

通过多少线程可以同时对这个方法(方法m)调用对象x?
可以是该方法被调用的事实,假设100线程对我的应用程序有瓶颈?

By how many threads can be this method (method m) called on object x simultaneously? Can be the fact that the method is called by, let's say, 100 threads a bottleneck for my application?

感谢。

推荐答案

其他人已回答了您的直接问题。

Other's have answered your direct question.

我想清除可能是您误解的一部分...如果是,则是危险


方法m是不同步的,它不需要是因为它不会真正改变X类型的对象x的状态。

Method m is NOT synchronized and it doesn't need to be since it doesn't really change the state of the object x of type X.

这不是一个足够的条件。不改变状态的方法通常也需要同步。

That is not a sufficient condition. Methods that don't change state typically need to be synchronized too.

假设你有一个简单的getter和setter类Test:

Suppose that you have a class Test with a simple getter and setter:

public class Test {
    private int foo;

    public int getFoo() {
        return foo;
    }

    public synchronized void setFoo(int foo) {
        this.foo = foo;
    }
}

getter是线程安全的吗?

Is the getter thread-safe?


  • 根据您的规则,是的。

  • 实际上,不是。

为什么?因为除非调用 getFoo setFoo 的线程正确同步,否则调用 getFoo setFoo(...)可能会看到 foo 的过期值

Why? Because unless the threads that call getFoo and setFoo synchronize properly, a call to getFoo() after a call to setFoo(...) may see a stale value for foo.

这是其中一个令人讨厌的情况,你几乎所有的时间都会逃脱。但是偶尔,两个调用的时间会是这样的,这个bug会让你窒息。这种错误很可能会通过测试的裂缝,并且在生产中很难重现。

This is one of those nasty cases where you will get away with it nearly all of the time. But very occasionally, the timing of the two calls will be such that the bug bites you. This kind of bug is likely to slip through the cracks of your testing, and be very difficult to reproduce when it occurs in production.

只有当状态被声明为 final 时,才能从多个线程中安全地访问对象的状态,构造函数不会发布对象。

The only case where it absolutely safe to access an object's state from multiple threads without synchronizing is when the state is declared as final, AND the constructor doesn't publish the object.

这篇关于有多少线程可以同时调用对象的非同步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆