Re: Safety Of Non-Synchronized Collections
markspace wrote:
Steve wrote:
In other words, I got the message "Use the new StringBuilder wherever
possible.", what I want to know is, how can I be sure it is possible?
I have to second the suggestion to obtain a good reference on the
subject and read it. Java Concurrency in Practice is the only such good
reference I know, although the Java Language Specification is good too,
just a bit thick.
I kind of disagree with Lew's rule about final fields and immutability.
What you show lacks immutability.
It's too easy to mess up if you don't what you are doing. The
Not if you keep things immutable. That's the defense against not knowing
what you're doing.
following seems to fit Lew's brief description, but it isn't immutable,
Therefore does not seem to fit my definition.
You confuse me.
or thread safe:
I did say "immutable".
If you don't know what that is, either learn or give up programming.
public class ImmutableStringBuilder {
private final StringBuilder sb;
public ImmutableStringBuilder( StringBuilder sb ) {
this.sb = sb;
}
}
So it's hard to catch errors like this if you don't really understand
Java's memory model. (Memory model = multi-threading, for all intents
and purposes.) Check out the Memory Model section of the JLS, and get
JCiP. It's really the only way.
I agree, but many of the subtleties of multi-threaded programming in Java are
avoided by the use of immutable objects. Yes, you do have to understand what
immutable means. Thank you for illustrating that.
But you don't have to understand absolutely everything about concurrent programming
to get that much right. Nor do you have to be a master of concurrent programming,
not that that's really possible, to do any.
I read through JCIP and many of Brian Goetz's excellent articles on IBM Developerworks
about Java concurrency. The /happens-before/ relationship definitely helps one to reason
correctly about it. But it didn't make me a master, despite decades of experience in
concurrent programming. But I'm better than average.
Even with knowledge, it's just so much easier to rely on immutability. Lazy instantiation
is a false bargain.
--
Lew