Java thread safety of list

前端 未结 4 997
一个人的身影
一个人的身影 2021-02-05 19:00

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

4条回答
  •  滥情空心
    2021-02-05 19:30

    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:

    1. 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.
    2. Even this guarantee is void if any thread can obtain a reference to the original list. Make sure this doesn't happen.
    3. Get the functionality right first, then you can start worrying about synchronization being too slow. I very rarely encountered code where the speed of Java synchronization was a serious factor.

    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.

提交回复
热议问题