简体   繁体   中英

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. It is better to use enum classes for this use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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