同时调用singleton对象的Java方法 [英] Concurrently invoking Java method of singleton object

查看:108
本文介绍了同时调用singleton对象的Java方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于Java中多线程方法调用的问题。假设我们有一个单例对象,其类声明如下:

I've got a question regarding multiple-thread method invocation in Java. Let's say we have a singleton object, and its class declared as follows:

public class SomeClass {
    public void someMethod(SomeValueObject object) {

        if (object.condition1) {
            ...
        }
        if (object.condition2) {
            ...
        }
        if (object.condition3) {
            ...
        }

    }
}

我想知道这个单例对象是否被同时访问并且someMethod是否被不同的SomeValueObject实例调用,是否有可能随机线程发生变化 object 的引用是否是另一个线程的方法调用和搞砸事情?那么在方法范围内创建的字段呢?
我不知道的是,是否为调用该方法的每个线程创建了单独的Method上下文,或者对于调用它的所有线程,Method上下文是否相同?如果是后一种情况,我想我需要 synchronized 关键字来保证线程安全,或者为每个线程使用不同的SomeClass实例(如果我需要更快的内存优化执行) )。你能帮我解释一下这个问题吗?

I'm wondering if this singleton object is being concurrently accessed and its someMethod called with distinct SomeValueObject instances, is there a chance some random thread change the reference of object for another thread's method invocation and mess up things? And what about fields created inside method scope? What I'm not aware of, is there any separate Method context being created for every thread invoking the method, or Method context is the same for all threads invoking it? If it is the latter case, I guess I need the synchronized keyword for thread safety, or use distinct SomeClass instances for every thread (in case I need faster execution over memory optimization). Would you please explain the matter for me?

P.S。感谢你们的所有答案!

P.S. Thanks for all of your answers guys!

推荐答案

如果一切都是本地的,那么你的方法是线程安全的。每个线程在堆栈上都有自己的对象参数,并且它们不会相互干扰。

If everything is local, your method is thread-safe as is. Each thread will have its own object argument on the stack, and they won't interfere with each other.

如果两个线程调用此方法,则可能会出现并发问题与参数相同的对象,或者如果其中两个对象共享某个状态,但这不是单例的问题。这是共享状态的问题,必须正确同步。

You could have concurrency problems if two threads invoke this method with the same object as argument, or if two of those objects share some state, but that's not the problem of the singleton. It's the problem of the shared state, which must be properly synchronized.

良好的经验法则:无状态对象是线程安全的。具有不可变状态的对象是线程安全的。如果没有正确同步对共享状态的访问,则具有可变状态的对象不是线程安全的。

Good rule of thumb: a stateless object is thread-safe. An object with immutable state is thread-safe. An object with mutable state is not thread-safe if it doesn't properly synchronize access to the shared state.

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

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