Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: synchronized over pointers to objects?

Let's say I have list_a which I need to have synchronized access to. Now if I define a pointer to this object list_A

List<...> list_a=Collections.synchronizedList(new ArrayList<JmDNS>());
List<...> list_A=list_a;

can I synchronize over List_A and assume that access to List_a is synchronized? This is because list_a is from a different class with private access and it is being accessed from within that class.

like image 371
Maths noob Avatar asked Feb 20 '26 22:02

Maths noob


1 Answers

Yes, they reference the same object which is a synchronized list.

Note

I assume that you are aware that you synchronize only method calls on the list by using synchronized list.

Suppose you have something like this:

if (list_A.size() > 0) {
   Object element = list_A.remove(0);
}

Using a synchronized list alone does not make this a thread safe sequence of operations, because two threads can simultaneously evaluate the if condition to true, and then both can try to remove the first element from the list.

You can solve it this way:

synchronized(list_A) {
    if (list_A.size() > 0) {
       Object element = list_A.remove(0);
    }
}
like image 90
Dragan Bozanovic Avatar answered Feb 23 '26 11:02

Dragan Bozanovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!