This week's book giveaway is in the Agile and Other Processes forum.We're giving away four copies of The Little Book of Impediments (e-book only) and have Tom Perry on-line!See this thread for details.

SCJD with J2SE 5 thread doubt

kavithakaran kanapathippillai

Greenhorn

Posts: 10

posted 9 years ago

I am new to SCJD. I am following andrews SCJD with J2SE5 book. I have some problems in understanding the following code. can any one please help me? For me, it seems that Ice cream man might be accessing a corrupted ice cream dish to service the ice cream.

My Question is Say, a child thread is taken out of cpu time in the middle of line 63(since dishes is an array list this is possible), and IceCreamMan thread was give cpu time and in line 39 it picks the incompletely filled array list. the data in the list picked up by icecream man will be a corrupted one. Is this correct?

The method being a private one, it is not accesible from outside. So take a look from where it is called. If it is called from inside a synchronized code, it is ok. If not, the get method of the dishes list (I assume it is a LinkedList or an ArrayList) is not synchronized, and it is indeed a problem.

That's my understanding, but I don't have the book, so just by looking at fragments of code... you know...

Regards,

Romeo

SCJP 1.4, SCJD, OCE EJBD 6

kavithakaran kanapathippillai

Greenhorn

Posts: 10

posted 9 years ago

Thanks Romeo, It is not called from a synchronized block.so it should be a problem. If serveIceCream() method is changed into synchronized method, this will be fixed. is it correct

Now that you posted the entire class I can add some more comments. In the IceCreamMan class, the instance variable that is accessible from more than one thread is the dishes list. This list is accessed from outside through the public method requestIceCream and from the thread created by itself, in the run() method. This means, that the dishes list can be modified by two threads, correct? We know that the ArrayList does not have synchronized methods, so we should take care when an add/remove/get are performed on the list. There is one mistake in your synchronization. First, we usually call notify() only if we have somewhere in the code a wait(). Second, take care that requestIceCream is synchronized on this (that is IceCreamMan object) and inside private void serveIceCream() you synchronize on currentDish, that is a IceCreamDish object, so basically you want to synchronize on different objects. The problem that could arise here as I can see, is in the if (!dishes.isEmpty()) line. To be really paranoid you could put this line inside a synchronized block (on IceCreamMan.this object), but I don't think it really matters. Because if isEmpty() returns true when it really has an element in it, it's not such a big deal. It will catch the added element on the next iteration. I hope I didn't confused you further, but this is my understanding on the code you posted.