简体   繁体   English

在多线程程序线程中执行类的静态方法是否安全?

[英]Is execution of static method of a class in multi-threaded program thread safe?

I have a static method in a class that runs some calcs, here is code snippet: 我在一个运行一些计算的类中有一个静态方法,这里是代码片段:

public MyClass {

MyClass(){}

public static float runCalcs()
{
    float sum;
    Float[] floatArray = map.entrySet()
                        .stream()
                        .map(key -> key.getKey().getPrice())
                        .toArray(size -> new Float[size]);

    for(int i=0; i<floatArray.length; i++) {
        sum += floatArray[i];
    }   

    return sum;
}

}

My question is when I execute this method from a thread like so: 我的问题是当我从这样的线程执行此方法时:

float retVal = MyClass.runCalcs();

Is this a thread safe execution of static method or do I need to synchronize or lock MyClass.RunCalcs() to make it thread safe. 这是静态方法的线程安全执行还是我需要同步或锁定MyClass.RunCalcs()以使其线程安全。
In my application, multiple threads will be executing this method simultaneously. 在我的应用程序中,多个线程将同时执行此方法。
Please let me know. 请告诉我。
Thanks in advance! 提前致谢!

Thread safety is not a questions about methods or classes. 线程安全不是关于方法或类的问题。 Thread safety is a question about shared data . 线程安全是关于共享数据的问题。

Your shared data is not safe if a method running in one thread could temporarily put the data into a state that you would not want the same method or any other method running in a different thread to see. 如果在一个线程中运行的方法可能暂时将数据置于您不希望相同方法或在不同线程中运行的任何其他方法看到的状态,则您的共享数据是不安全的。

Your runCalcs() method looks at map which presumably is a Map instance, and which presumably is shared with some other thread. 你的runCalcs()方法查看map ,它可能是一个Map实例,并且可能与其他一些线程共享。

Is there any way that the other thread could change the contents of the map while runCalcs() is iterating over the map's entrySet() ? runCalcs()迭代地图的entrySet() ,有没有其他方法可以改变地图的内容? If so, then your code is not safe. 如果是这样,那么您的代码就不安全了。

The way to make it safe is to change runCalcs() lock a lock while iterating, and also, change every method that could update map in a different thread to lock the same lock while changing map . 使其安全的方法是在迭代时更改runCalcs()锁定锁,并且还更改可以更新不同线程中的map 每个方法以在更改map锁定相同的锁

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM