• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I have a doubt (Monkhouse and Camerlengo)

 
Shlomo Hillel
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

In the Child and IceCreamMan example (Ch. 4), the two threads use

private List<IceCreamDish> dishes = new ArrayList<IceCreamDish>();


defined in IceCreamMan for communicating.

Although the requestIceCream() is synchronised, the code that removes the dish after serving (dishes.remove (currentDish) is NOT!!!

There is a possibility that a Child will add a dish while the IceCreamMan is removing another.

Since the ArrayList is not synchronised (unlike Vector), don't you think that this is a problem?

Please clarify.

Regards,

Shlomo
 
Andrew Monkhouse
author and jackaroo
Marshal Commander
Pie
Posts: 12007
215
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shlomo,

Interesting. Child and IceCreamMan do not use the dishes object for communicating, they use the Child's IceCreamDish for communicating. And if that was all there was to it, I would have been safe with that code.

However, the Child's thread can add to dishes object at the same time that the IceCreamMan's thread is removing from it. So, yes, you are correct: the removal code needs to be in a synchronized block. The following synchronization will fix the problem:Regards, Andrew
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic