Search code examples
javacollectionssynchronize

Java: Rule Of Thumb For Using Synchrozined Collections?


I was reading this Stackoverflow thread about using StringBuilder versus StringBuffer.

The bottom line seemed to be that the two collections were the same thing except that a StringBuffer is synchronized, is a thread safe and does a little less well in performance as compared to StringBuilder which are not those things.

Someone brought up how a similar relationship existed between ArrayList and Vector.

Is it a good (safe) rule of thumb to NOT use synchronized collections ( or anything else ) unless I am consciously creating multiple threads?

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?

Am I safe using non-synchronized collections as long as I don't create new threads intentionally?


Solution

  • Use unsynchronized things until you're sure that you need synchronization.

    Part of the issue with e.g. StringBuffer and Vector is that they're not always synchronized in the right way. For Vector, it's not always what you need to have every operation be synchronized individually; frequently what you actually want is to synchronize blocks of operations...for which Vector isn't necessarily any better than ArrayList or a Collections.synchronizedList.

    When you know you're using concurrency and multiple threads, then work out the details of what synchronization you need, but just swapping StringBuffer in for StringBuilder will only give you a false sense of security -- even if you decide to use concurrency later, that's not necessarily the right kind of concurrency.

    (If you're not currently using threading, then it's absolutely fine -- even recommended -- to find-and-replace StringBuffer to StringBuilder. The above arguments are for the reverse direction.)