简体   繁体   中英

Java String immutability vs instances of String objects

In Java strings are special .

Since string literals with the same contents share storage in the common pool, Java's String is designed to be immutable. That is, once a String is constructed, its contents cannot be modified. Otherwise, the other String references sharing the same storage location will be affected by the change, which can be unpredictable and therefore is undesirable.

What if I synchronize on a String ? Will I lock across all instances of String sharing the same contents ?

For example : I have a multithreaded class which reads and writes from data files. There is 1 file per day and I want to synchronize read and writes to the same file so as to prevent unpredicatble behaviour. Can I simply synchronize on the filename (String) ?

You could intern the string, but it's a bit opaque to the next person who has to maintain the code. I'd suggest you create a File object or a separate Object called fileLock (say) to represent the intention more clearly.

You can do it with String.intern() :

String fileName = "fileName";
fileName = fileName.intern();
synchronized (fileName) {

}

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