Reputation: 1802
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.
Upvotes: 3
Views: 273
Reputation: 23562
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);
}
}
Upvotes: 1
Reputation: 390
Why not using java.util.Vector ?
http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html
just quoting:
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the vector is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. The Enumerations returned by the elements method are not fail-fast.
Upvotes: 0
Reputation: 277
You need not to synchronize list_A again as the reference list_A & list_a are pointing to the same list which is synchronized.
But you need to synchronize around the list when you iterate it. A common use case with a synchronised collection like this is to add to the list in multiple threads, but to iterate it only at the end when all tasks have complete.
If you are iterating after all the updating threads are done than don't worry about synchronization that time.
Upvotes: 0
Reputation: 122008
can I synchronize over List_A and assume that access to List_a is synchronized?
No. You need not to synchronize List_A
again. Because List_A
already pointing to list_a
which is synchronized.
List<...> list_A=list_a;
That line alone means, you are not creating any new object, just referencing an existing one.
Upvotes: 0