Re: synchronized using String.intern()

On Fri, 30 Jan 2009, Paul J. Lucas wrote:

I've seen differing opinions on whether it will do as one would expect to do something like:

synchronized ( myString.intern() ) {
// ...

that is: for a given, unique string (say "foo"), does String.intern() guarantee that:

s.intern() == t.intern() iff s.equals( t )

assuming s != null && t != null? I.e., does it guarantee the same object for a string composed of the same characters? If yes, then synchronizing on it should work as one would expect, right?

The use case is to prevent concurrent access to a particular file, e.g.:

File f = ...;
synchoronzed ( f.getCanonicalPath().intern() ) {
// ...

If this will *not* work, why not? And how can I achieve what I want?

I think that's a pretty cunning hack, and i think it'll work.

Up to, as Lew says, degeneracy in the canonical path. If the file exists before you start doing all this, and you're not using a case-insensitive filesystem on an OS which doesn't handle it well (eg VFAT on linux), and you don't have any hard links or other weirdness like bits of the local filesystem mounted as loopback network shares etc floating around, you should be fine.


Only men's minds could have mapped into abstraction such a territory