3

CopyOnWriteArrayList methods that mutate its state (add, set, etc) acquire the lock following way:

final ReentrantLock lock = this.lock;
lock.lock();

Why does it save this.lock into a local variable? this.lock is declared final so it can't change anyway. Why couldn't we just write this.lock.lock()? Does it have some implication on concurrency or is it just a matter of taste?

Here is the link to source code.

Konstantin Milyutin
  • 11,946
  • 11
  • 59
  • 85
  • Yes, I think the idea is to not block. So that way updates never block when someone is iterating through the list (which might take a while). Not blocking can be a big deal in concurrency performance. – markspace Nov 03 '16 at 22:13
  • @markspace The question is why save the lock in a `final` local variable? – John Kugelman Nov 03 '16 at 22:17
  • Yeah I'm actually confused. Now I think he's asking why create a local variable for `lock`. I think the OP should clarify. – markspace Nov 03 '16 at 22:18
  • C.f. this code here: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/CopyOnWriteArrayList.java#CopyOnWriteArrayList.set%28int%2Cjava.lang.Object%29 – markspace Nov 03 '16 at 22:19
  • I thought the question was clear, but I clarified it anyway. – Konstantin Milyutin Nov 03 '16 at 22:21
  • You should add more code to your example; it is not clear that those variables are local and not instance fields. 99% sure this is just taste, there's no difference in code operation if the instance variable (`this.lock`) is used instead. – markspace Nov 03 '16 at 22:23

0 Answers0