Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.104 :

Posted: Sat May 14, 2011 11:05 am
by ETS User
Not sure why the option "It cannot be made thread safe if method dumpMethod() is removed" is not correct. There is still the non-synchronized addMessage method so my understanding it that just removing the dumpMethod will not make it thread safe.

Re: About Question com.enthuware.ets.scjp.v6.2.104 :

Posted: Sat May 14, 2011 12:17 pm
by admin
The class can be made thread safe even if the dumpMethod() is removed. By adopting other means. It does not say that the class cannot be made thread safe just by removing dumpMethod(). dumpMethod() is not the only thing affecting its thread safety.

But you are right. I think the option is too confusing. It should be "It cannot be made thread safe by removing dumpMethod()." or "It cannot be made thread safe unless method dumpMethod() is removed."

Re: About Question com.enthuware.ets.scjp.v6.2.104 :

Posted: Mon Apr 14, 2014 3:37 am
by cosmindumy
From my understanding, by replacing StringBuilder with StringBuffer MessageBuffer is not thread safe.
If thead1 and thread2 writes and read from MessageBuffer, when thread1 calls dumbMessage to print the message it could be altered by thread2.
So only if both public methods are synchronized the class is thread safe.

Re: About Question com.enthuware.ets.scjp.v6.2.104 :

Posted: Mon Apr 14, 2014 4:26 am
by admin
StringBuffer's methods are synchronized and so if you replace StringBuilder with StringBuffer, you don't need the methods of MessageBuffer to be synchronized at all. The situation that you described cannot happen with StringBufer because when dumpMessage tried to get the String from StringBuffer, no thread can execute append() on sb.

HTH,
Paul.

Re: About Question com.enthuware.ets.scjp.v6.2.104 :

Posted: Thu Oct 23, 2014 12:12 pm
by piotrkmiotczyk
Nowhere in the question is it suggested that messages have to be stored in adding sequence. Perhaps they are loosely connected - lines in fortune cookies, not lines in a novel. Perhaps each one contains a time code, with which they can be later sorted. Also the method that reads it looks entirely resistant to end of file/empty text events.

By comparison, the Concurrency questions had code where uncontrolled thread access could create infinite loops, skipping or duplicate entries, etc.

So, given (no) requirements is it still 'not thread safe'?

EDIT: Unless sb.append(msg) isn't itself atomic and two String messages can end up with their chars intermixed...?

Re: About Question com.enthuware.ets.scjp.v6.2.104 :

Posted: Thu Oct 23, 2014 8:36 pm
by admin
Yes, if you use StringBuilder, it is possible for two messages to have their chars mixed up.