Chris Hurst wrote:
David Spades wrote: IMO, getSize() doesn;t need synchronizing. lets say another thread is in the middle of adding a new element when getSize is called, so the new element is not yet included in the count, which is valid since the adding is not yet finished, right?
this is my reasoning. is there any fault in this?
getSize needs to be synchronized. If one thread does all the adds and another was created at the same time as the first but never synchronizes on a common object with the mutating thread, getSize could in theory always return 0 for the second thread always/for ever i.e. empty collection regardless of any modifications by other threads because it never looks for change, the answer was zero the last time so surely its still zero as this thread hasn't modified it. By not not saying getSize is synchronized you are effectively allowing the reading thread to ignore all other threads changes if it decides its more efficient to do so i.e. your saying you don't care but you obviously do. In reality your getSize will most likely be observed to work (ish) but why take the risk ??
Originally posted by Chandra Kota:
As per my understanding, once a thread completes its run() method, it moves to dead state. i.e it can not be thread of execution again. In trying to invoke start() method again on that reference, we will have an exception in place. But thread object itself is not nullified. The object is still on heap and has a valid reference.In fact, we can still invoke any other methods defined in our thread object except start(). Now since the object is having a reference, it is basically not eligible for GC. Correct me if I'm wrong. Thanks in advance.