Search code examples
javamultithreadingsynchronizationtomcat7

Hapshmap vs tomcat app server


I got one question from interview, are you used Hashmap or Hashtable in the current project?

My Answer : I said I have used Hashmap not Hashtable, because it is not multithreaded environment(project does not have multiple thread processing).

Q :Tomcat creates multiple thread for request processing then why are you using Hashmap?

My Ans :

It will create multiple thread in and each thread have it's own threadstack memory for keep those objects and processing the requests.

is it my answer was correct if not please correct me the ans for this question.


Solution

  • It depends on context.

    If you have some shared datastructure that is used between requests, then yes, you'd need some kind of synchronization. You might want to consider a java.util.concurrent.ConcurrentHashMap however, which offers lower-contention reading than a Hashtable.

    You are right though that if you create the structure inside a request, and do not share it between threads / requests, a HashMap would be fine.

    Just to flesh this out, to reply to a comment:

    Imagine you are writing an endpoint that accepts an array of key/value pairs. If this endpoint repeatedly needs to refer to these request values according to the key, but the values aren't needed by any other request, you may wish to put them into a HashMap. If the server services n concurrent requests to the same endpoint concurrently, it would create n instances of the controller, each executing the method with their own stacks (as you pointed out), and their own copy of the HashMap. Importantly, each instance of the HashMap will never have to deal with concurrent access form multiple threads.

    Now imagine a second scenario where site wants to stop users from trying to log in too often. You could use a dictionary in the application context, that stores counts of each user's login activity to try to find if an account is being attacked (by the way, this is illustrative - don't implement this scenario in this way). In this case, n simultaneous requests would all be updating the dictionary at the same time. If multiple threads attempt to add new keys at the same time, this could kill the application.

    Your comment below refers to application / sessions contexts. The session is still shared; even though it belongs to one user, that user could make multiple concurrent requests to the server, which all update the same HashMap, e.g. their shopping cart