Anna Klein
Anna Klein

Reputation: 2171

Correct working with Collections.synchronizedList

I am not sure how to properly use the Collections.synchronizedList() implementation.

I have these two:

   public synchronized static List<CurrencyBox> getOrderList() {
        return Collections.synchronizedList(orderList);
    }

and

 public static List<CurrencyBox> getOrderList() {
        return Collections.synchronizedList(orderList);
    }

So as far as I understood, synchronizedList really returns the orderList and not a copy, correct?

So If I want to gurantee atomic operations, like add and remove, which of the implementation above is correct?

And does something maybe changes with Java9? Or is it still the way to go or have you any other suggestion?

Thank you

Upvotes: 1

Views: 654

Answers (2)

linead
linead

Reputation: 1636

Without context it's a bit hard to tell, from the snippets provided neither give you guaranteed atomic operations.

The documentation states:

Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.

So even if you synchronize the method the best you'll get is a guarantee that no two objects are creating the synchronized list at the same time.

You need to wrap the original orderList with Collections.synchronizedList to begin with and return the stored result of that each time.

private static List<CurrencyBox> orderList = Collections.synchronizedList(new ArrayList<CurrencyBox>());
public static List<CurrencyBox> getOrderList() {
    return orderList
}

Upvotes: 2

Divyesh Kanzariya
Divyesh Kanzariya

Reputation: 3789

A synchronized list only synchronized methods of this list.

It means a thread won't be able to modify the list while another thread is currently running a method from this list. The object is locked while processing method.

As an example, Let's say two threads run addAllon your list, with 2 different lists (A=A1,A2,A3, B=B1,B2,B3) as parameter.

  • As the method is synchronized, you can be sure those lists won't be merged randomly like A1,B1,A2,A3,B2,B3

  • You don't decide when a thread handover the process to the other thread so you can either get A1,A2,A3,B1,B2,B3 or B1,B2,B3,A1,A2,A3.

Credit : jhamon

Upvotes: 2

Related Questions