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.

tom

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



Relevant Pages

  • Re: synchronized using String.intern()
    ... that is: for a given, unique string, does String.internguarantee that: ... 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, ... with each canonical File object. ...
    (comp.lang.java.programmer)
  • synchronized using String.intern()
    ... I've seen differing opinions on whether it will do as one would expect to do something like: ... that is: for a given, unique string, does String.internguarantee that: ... 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, ...
    (comp.lang.java.programmer)
  • Re: synchronized using String.intern()
    ... Paul J. Lucas wrote: ... that is: for a given, unique string, does String.internguarantee that: ...
    (comp.lang.java.programmer)
  • Re: enabling and disabling of agents question
    ... Thank you again Paul. ... > DJC, ... > yes - you need to stop synchronizing to stop the job, and disabling it ... > Synchronizing' are actually independant of this property though. ...
    (microsoft.public.sqlserver.replication)