简体   繁体   中英

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.

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);
    }
}

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM