Hello. A question:

  1. In javadoc it is written that for thread-safe access to an ArrayListу it needs to be decorated through Collections.synchronizeList . I understand that this method simply returns the list methods of which are synchronized , is that so?

  2. From the same javadoc:

     List list = Collections.synchronizedList(new ArrayList()); synchronized(list) { Iterator i = list.iterator(); // Must be in synchronized block while (i.hasNext()) foo(i.next()); } 

It is imperative that the list of users over it: ...

Why in this case manually synchronize through synchronized(list) ? Or should it be done only when working with iterators, and not necessarily if you access the sheet via get() , add() , set() ? Thank.

  • I will ask a counter-question: why use non-synchronized classes instead of synchronized ones in a multi-threaded program and use techniques called "screwing crutches"? Vector? SynchronizedList? - jmu
  • one
    @jmu, be careful with Vector . One of his mention causes the wrath of the gods :) By the way, the decorator itself is not a crutch, and in some cases this approach may be useful. But only in some. - cy6erGn0m

1 answer 1

  1. Well, look what Collections.synchronizedList does in the IDE control-click and read what is written. But generally, you will find that yes, there every method is synchronized.
  2. Accordingly, this fact is the reason that there is a need to synchronize separately. The thing is, the iterator will break if someone modifies the list between next () calls. To avoid this, you have to make a larger synchronized block.
  3. And yes, the violation of the internal state of the list inside the set methods has not been canceled: a simultaneous call to the set method from different threads with a high probability will destroy the list. Therefore, you need to do synchronizedList. Well, or you can just synchronize your hands everywhere, and not wrap. Personally, I usually do this and rarely use this decorator. It is usually useful if you give the list somewhere outside, which I try to avoid by hook or by crook.
  • That is, roughly speaking, this is necessary so that while the iterator is working (it has the blocking object of this sheet), no one else could call set() add() , for calling which the same blocking object is needed? So? - Vladimir
  • Yes, precisely for this. - cy6erGn0m
  • And yes, the violation of the internal state of the list inside the set methods has not been canceled: >> it is written in javadoc that set is not a structural operation and it can be not synchronized. So what to do with set ()? - Vladimir
  • Where did you find that there? Read the set method for ArrayList. Obviously, it is not thread safe. Or do you mean synchronizedList? - cy6erGn0m
  • @Vladimir, better do all locking (synchronization) yourself. Then it will be easier to understand. - avp