Is it a good (safe) rule of thumb to NOT use synchronized collections ( or anything else ) unless I am consciously creating multiple threads?
No it is not.
There are situations where multiple threads are involved, even though you don't consciously create them. For example, any application that uses Swing or Servlets has the potential for interactions between application code on different threads. (And you could even argue that you don't explicitly create threads if you use a standard thread-pool implementation.)
And further more, using a synchronized collection does not necessarily buy you thread safety.
But you are correct in the sense that using a synchronized data structure when there is no possibility of multiple threads using the data structure is (somewhat) wasteful. But nowhere like as wasteful as in the old days when mutexes were expensive.
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?
By understanding your code. Can the StringBuilder
be seen by other threads? If not, then it safe to use it. Otherwise, the threads that share the StringBuilder
need to synchronize. One way to do that might be to use a StringBuffer
, but that won't necessarily give you the right synchronization granularity.
Here's a simple example:
public String nTimes(String str, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) sb.append(str);
return sb.toString();
}
In the above, the StringBuilder
in sb
can never be seen by another thread, so there is no need to synchronize it.