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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With