small medium large xlarge

Generic-user-small
22 May 2017, 08:21
daition (2 posts)

Hi, this is a good book for java developers. I write here just want to get a confirm about the right understanding about the sample code.

At the end of Chapter 2, about the alien methods, I think the example for defensive copy is incorrect. In fact, the clone operation of listeners only cause a shallow copy for the ArrayList. As a result, listenersCopy and listeners still share the same elements in them, even though they are two separate ArrayLists. So I think it can not guarantee the effect stated below the sample code.

If I have any mistake please feel free to correct me.

Thanks!

Icon_pragsmall
22 May 2017, 11:08
Paul Butcher (38 posts)

Thanks for the kind words - I’m glad you’re enjoying the book, and glad that you’re thinking carefully about the sample code.

You are correct that calling clone on listeners only performs a shallow copy. But in this case, a shallow copy is good enough.

The defensive copy that you’re mentioning solves two different problems:

  1. The first is a possible deadlock caused by calling an alien method while holding a lock.
  2. The second is a possible concurrent modification exception, which could happen if a listener calls removeListener within its onProgress method.

Problem 1 is solved by removing the synchronized from updateProgress, and instead only holding the lock while making the defensive copy. So no lock is held when we call each listener’s onProgress method.

Problem 2 is solved by iterating over a different list than the one that would be modified if a listener calls removeListener within its onProgress method. It doesn’t matter that this list contains the same elements as the one we are iterating over, as we’re not protecting against those elements changing, but the list they’re contained within.

If you’re still unconvinced, perhaps you could try to write a test which causes the problem you’re worried about. I don’t expect that you will be able to do so (but would be delighted to be proven wrong!).

Thanks for taking the time to get in touch,

Paul

Generic-user-small
23 May 2017, 03:41
daition (2 posts)

Paul,

You are right. The range of synchronized code become smaller, only one lock is used here, so a shallow copy is enough.

Thank you for your explanation.

You must be logged in to comment