Re: Usefulness of "final" (Was: Re: Inserting In a List)
In article <kjs56q$hib$1@dont-email.me>, markspace
(markspace@nospam.nospam) says...
On 4/7/2013 8:28 AM, Wanja Gayk wrote:
public class Foo{
private int value;
private Foo(int value){this.value=value;}
public static Foo createFoo(int value){return new Foo(value);}
public int getValue(){return value;}
}
..is both immutable, thread safe and can't be overridden either, without
No, he doesn't say that, and no, this class isn't thread safe. Normal
POJO classes aren't thread safe. Adding a factory method doesn't help.
In order for this class to be thread safe 'value' would have to be made
visible somehow. You need volatile, a synchronized block, or something
similar. Please read the JLS (and JCIP, again) and note section 17
Threads and Locks. The whole point of that section is that regular
writes aren't thread safe.
You're right in that regard, in rare cases a second thread could see the
"0" default. But you know it's check mate in 1 draw, my friend.
Just watch this:
public class Foo{
private volatile int value;
private Foo(int value){this.value=value;}
public static Foo createFoo(int value){return new Foo(value);}
public int getValue(){return value;}
}
Now that's immutable and thread safe and still there is no "final" used.
Check mate!
Kind regards,
-Wanja-
--
...Alesi's problem was that the back of the car was jumping up and down
dangerously - and I can assure you from having been teammate to
Jean Alesi and knowing what kind of cars that he can pull up with,
when Jean Alesi says that a car is dangerous - it is. [Jonathan Palmer]
--- news://freenews.netfront.net/ - complaints: news@netfront.net ---