I have a List, which is to be used either in thread-safe context or in a non thread-safe one. Which one will it be, is impossible to determine in advance.
In such specia
If you fill your list and then wrap it in the same thread, you'll be safe.
However there are several things to bear in mind:
Collections.synchronizedList()
only guarantees you a low-level thread safety. Complex operations, like if ( !list.contains( elem ) ) list.add( elem );
will still need custom synchronization code.Update: I'd like to add a few excerpts from the JLS to hopefully clarify matters a bit.
If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
This is why filling the list and then wrapping it in the same thread is a safe option. But more importantly:
This is an extremely strong guarantee for programmers. Programmers do not need to reason about reorderings to determine that their code contains data races. Therefore they do not need to reason about reorderings when determining whether their code is correctly synchronized. Once the determination that the code is correctly synchronized is made, the programmer does not need to worry that reorderings will affect his or her code.
The message is clear: make sure that your program, executed in the order which you wrote your code in, doesn't contain data races, and don't worry about reordering.