Pages 83 - 91 of “The Well-Grounded Java Developer” by Evans and Verburg.
A class is provided to you that can get into an inconsistent state. The included
main method demonstrates that the inconsistency can happen. Modify this class using only the
syncronized keyword to ensure it can never become inconsistent. What is the fewest number of
synchronized keywords required?
The solution is provided in this attached java file. The minimum number of
synchronized keywords required is 2.
You have been provided with some Java code that demonstrates the different states a
Thread might be in. Download this code and run it to see what it does.
You should see that it starts up 10 threads all trying to read the time from a webservice. The webservice doesn’t like DOS attacks, so it rejects requests if they come too fast. For that reason the method that tries to get the time will wait some (random) amount of time before asking. As the program runs, it will show you the state of each of the 10 threads. Inspect the source code to see what each code means.
You should experiment with the effect that the
synchronized keyword will have. What happens if you synchronize the
getTime method? Did the program output show you what you expected?
The Official Java Tutorial has an example of how you can create a deadlock using object locks. Inspect this example, run it, and work out which thread has ownership of each lock at the point where the program locks up. Is there a way to unlock the program? Can you unlock it _without touching the