Its simple, the UnsafeGuestbookServlet
is initialized once, and the doGet
or doPost
methods are invoked by multiple threads parallel.
Note that the implementation of HashSet
is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.
Hence to synchronize the HashSet
we used Collections.synchronizedSet()
. Now the HashSet is synchronized, and accesses to this particular HashSet for writing would be controlled one at a time.
If yu want more info on threading, thread safe approach why and how etc., better read this http://www.tutorialspoint.com/java/java_thread_synchronization.htm. BTW, in simple words its this, when two or more people are allowed to get a single same thing at the same time, there would be a race condition or a condition of instability. If your code permits this to happen its thread-unsafe :-)
And one more point to this, all depends on how you handle it in your code too. If you think, no 2 threads can overwrite or delete the same value from the datastructure, well you dont want to mind the thread safety. Please be aware of why thread safety is important, and in which cases its most important.