Can a class with getters separate from input processing methods be
considered "thread-safe"?
I was reading though a book on Java and there was this exercise question
where they declared a class with one private variable, one public void
method that did some expensive operation to calculate and then set the
private variable, and a second public method to return the private
variable. The question was "how can you make this thread-safe" and one
possible answer was "synchronize each of the two methods" and one other
possible answer was "this class can not be made thread-safe".
I figured the class could not be made thread-safe since even if you
synchronize both methods, you could have a situation that Thread1 would
invoke the setter and before Thread1 could invoke the getter, Thread2
might execute and invoke the setter, so that when Thread1 went and
retrieved the result it would get the wrong info. Is this the right way to
look at things? The book suggested the correct answer was that the class
could be made thread safe by synchronizing the two methods and now I'm
confused...
No comments:
Post a Comment