klonq
klonq

Reputation: 3607

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) ?

Upvotes: 2

Views: 98

Answers (2)

ᴇʟᴇvᴀтᴇ
ᴇʟᴇvᴀтᴇ

Reputation: 12751

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.

Upvotes: 7

xingbin
xingbin

Reputation: 28289

You can do it with String.intern():

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

}

Upvotes: 2

Related Questions