简体   繁体   English

使用以下类的实例在线程之间共享有什么问题?

[英]What is the problem with using an instance of the following class to share between threads?

I'm being asked what is the problem of using an instance of the following class to share between threads.有人问我使用以下类的实例在线程之间共享有什么问题。 What are the risks?有哪些风险? And what are possible solutions?什么是可能的解决方案?

public class States {

    private String[] states = new String[] {
        "UNK", "NEW", "RUNNING", "DONE"
    };

    public String[] getStates() {
        return states;
    }
}

The problem with this code is that although arrays are immutable in java but because you expose a reference to the array, nothing prevents anyone to reassign the whole array with a new one.这段代码的问题在于,尽管数组在 Java 中是不可变的,但是因为您公开了对数组的引用,所以没有什么可以阻止任何人用新数组重新分配整个数组。 It is better to use enum classes for this use case.对于此用例,最好使用枚举类。

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

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