Sync List Sync

If I have something like this snippet -

public List<E> list =  Collections.synchronizedList(new ArrayList<E>());

then if I do some operations inside the method -

boolean absent = !list.contains(x);             // Statement 1
if(absent)                                      // Statement 2
    list.add(x);                                // Statement 3

Do I need to wrap the above statements inside synchronized(list){ ... }to do the operations atomic?

+4
source share
3 answers

Do I need to wrap the above statements inside synchronized(list){ ... }to make atomic operations?

Yes, otherwise yours Listcan be changed elsewhere in your code in the time window that you call containsand addthat can cause race condition problems .

Does that make me what good Collections.synchronizedList?

Collections.synchronizedList List , , . contains add, , , add, contains , . - , List .

+3

, , , (, ..).

+2

Correctly. Theoretically, anything could happen between your statements 1 and 3; this way: if you want them to happen "atomically"; then you need to somehow turn them into a "single transaction".

Use synchronized(list)is a smart way to get there.

+1
source

Source: https://habr.com/ru/post/1655952/


All Articles