On Jan 30, 3:00*pm, "Paul J. Lucas" <p...@nospam.lucasmail.org> 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?
Javadocs are your friend:
<http://java.sun.com/javase/6/docs/api/java/lang/String.html#intern()>
> for any two strings s and t,
> s.intern() == t.intern() is true if and only if s.equals(t) is true.
It uses almost the exact same wording that you did.
> The use case is to prevent concurrent access to a particular file, e.g.:
As Mark Space pointed out, synchronization between Java threads is not
related to file access.
> File f = ...;
> synchoronzed
Watch your spelling!
> * * * * ( f.getCanonicalPath().intern() ) {
> * * * * * * // ...
> * * * * }
>
> If this will *not* work, why not? *And how can I achieve what I want?
You will synchronize on the object that represents the canonical path
to the file. That canonical path will change depending on whether the
file exists or not, so the synchronization would end up being on
different objects, i.e., no synchronization at all.
There are ways to access the file without using the canonical path,
and those will not be synchronized.
None of the synchronization you do get will have anything to do with
file access, only with multithreaded execution of critical sections of
code within a single JVM.
The fact that the words "concurrent" and "synchronize" occur in
different contexts (memory, execution, file access) does not by itself
guarantee that the words mean the same thing across all contexts.
Different things are being synchronized in different ways for
different kinds of concurrency. In your example, even the things in
the same context, JVM threads, will be locking different objects and
not synchronizing correctly.
--
Lew
|