0

Before I ask anything you might tell me to read docs. But I am still a beginner and I am not handling docs so easily. My question is does iterator in SynchronizedList block 'entire iteration process (loop)' or just its methods?

Meaning: Can another thread do some work on synchronizedList instance while iteration is 'going on'? Or it can do some work after thread that called next(), as I noticed next() is also synchronized.

I would appreciate any help, thanks :)

Ana Maria
  • 475
  • 2
  • 11

1 Answers1

0

does iterator in SynchronizedList block 'entire iteration process (loop)' or just its methods?

Just its methods.

There is no way for the class to detect if it is being used in a loop.

If you need the list to be synchronised for the entirety of a loop, externally synchronize on the list:

synchronized (list) {
  for (E element : list) { ... }
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • But that still doesn't mean other thread can't modify list. I checked implementation of basic methods, they have their own keys, meaning this won't work, will it? As your synchronized block uses different key.. – Ana Maria Aug 21 '20 at 18:14
  • @AnaMaria have you looked at the [Javadoc](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Collections.html#synchronizedList(java.util.List))? – Andy Turner Aug 21 '20 at 18:16
  • Yes. For example: public void add() uses synchronized (Vector.this). And you used list as a key. Meaning this won't work. As they are locked to 2 different keys – Ana Maria Aug 21 '20 at 18:18
  • @AnaMaria I mean: the Javadoc says this works, so if the version of the JDK you are using is written in a way such that this doesn't work, it's an incorrect implementation. Please provide details of which JDK/version you see "Vector.this" in, because I don't see it in the versions I'm looking at. – Andy Turner Aug 21 '20 at 18:23
  • Actually it is quite new (11.0.04) is my SDK. Yes in Vector methods are synchronized on Vector.this, while on SynchronizedList they are synchronized on final Object mutex; I kinda don't know how synchronizing on list in your case would help us unless we use same keys as internal implementation.. – Ana Maria Aug 21 '20 at 18:31
  • @AnaMaria have a look at what the value of `mutex` is. – Andy Turner Aug 21 '20 at 19:14