简体   繁体   English

如果在同步块之外声明/返回了返回值,该方法是否是线程安全的?

[英]Is a method thread-safe if the return value is declared/returned outside of a synchronized block?

public Foo getFoo(){
    Foo foo = null;

    synchronized(fooList){
        if(fooList.size() > 0){
            foo = fooList.remove(0);
        }
    }

    return foo;
}

Since foo is declared outside of the synchronized block, does the potential exist of returning bad data? 由于foo是在同步块外部声明的,因此是否存在返回错误数据的可能性?

Each thread instance calling getFoo() will have its own foo instance. 每个调用getFoo()线程实例将具有其自己的foo实例。 Thus foo is thread safe and doesn't need synchronization. 因此, foo是线程安全的,不需要同步。

What does "bad data" mean in this context? 在这种情况下,“不良数据”是什么意思? fooList may change asynchronously before synchronized(fooList) and after the corresponding closing brace, before return foo; fooList可能在synchronized(fooList)之前和相应的synchronized(fooList)括号之后, return foo;之前异步更改return foo; (more generally speaking, up to the moment the returned value is used.) What is your ultimate goal? (更一般地说,直到使用返回值为止。)您的最终目标是什么?

getFoo will not return stale data, since Foo foo is local variable AND fooList is synchronized getFoo不会返回过期数据,因为Foo foo是局部变量, fooList同步

Local variable is thread safe since each thread call will create a new Foo object, instead of sharing single object. 局部变量是线程安全的,因为每个线程调用都会创建一个新的Foo对象,而不是共享单个对象。 While instead variable is not thread safe, since multiple threads can access fooList , but in this case the fooList is already synchronized. 相反,变量不是线程安全的,因为多个线程可以访问fooList ,但是在这种情况下, fooList已经同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 同步语句之外的代码语句是否是线程安全的? - Are code statements that are outside the synchronized statement thread-safe? 是否遍历在同步块中检索的列表是线程安全的? - Is iterating over a list retrieved in a synchronized block thread-safe? 为什么即使使用同步方法,此代码也不是线程安全的? - Why is this code not thread-safe, even when using a synchronized method? 按同步方法返回值的块的同步跨度 - synchronized span for block by synchronized method return value 将对象分配给在同步块外部定义的字段 - 它是否是线程安全的? - Assigning a object to a field defined outside a synchronized block - is it thread safe? 使用与线程安全集合同步? - Using Synchronized with Thread-Safe Collection? Java多线程使用synchronized不是线程安全的 - Java multithreading not thread-safe using synchronized 如果从同步方法中调用方法,则内部方法对共享的可变数据的访问线程安全吗? - If a method is called from within a synchronized method, is the inner method's access to shared mutable data thread-safe? 在线程安全 Singleton 中,返回是否必须在同步块内 - In a Thread Safe Singleton does the return have to be inside the synchronized block 我们可以以线程安全的方式从方法中返回 Function 吗? - Can we return Function from a method in a thread-safe way?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM