When using java threads, one has to take care of 开发者_如何学Cthe basic problems that come with concurrency through synchronization etc.
AFAIK Tomcat also works with threads to handle its workload. Why is it, that I don't have to think about making my code threadsafe when it is running in Tomcat?
You do have to make your code thread safe in tomcat. Tomcat will invoke your code (i.e. your servlets) from multiple threads, and if that code is not thread-safe, you'll have problems.
Tomcat's threads are no different to any threads you create yourself.
To add on to what skaffman has mentioned, it might seem like you don't need to think about multi-threading when writing a webapp because the Servlet framework/API is oriented completely around implementing methods (service()
, doGet()
, doPost()
, etc) which are invoked once per HTTP request.
Therefore, in a simple application, you can implement these methods in your servlet and/or JSP or whatever and not think about what happens when multiple threads interact.
But the second you start having shared state between servlets or service methods, then without possibly realizing it you are dealing with multiple threads interacting, and if you aren't careful, you will eventually have multi-threading or synchronization issues. You will have to deal with this because in Tomcat (and I assume all servlet containers, although I don't know if it's required by the Servlet spec) each request is handled by (possibly) a different thread. Therefore if you receive two simultaneous requests, these will be handled by two separate threads concurrently (at the same time).
If you think that Tomcat makes your application thread safe write a Servlet with mutable member variables like a non-concurrent hashmap.
Then have the servlet put things in that hashmap for every request. It won't take long to get a lovely concurrency exception.
This is why in general for singleton-like components you have to be very careful with member variables because they are shared between multiple threads accessing the object.
Now the servlet container create a new transient object for every request (which is what some web app frameworks do) you could put behavior that interacted with the member variables in that transient object and be thread safe.
Because Java EE containers are written in such a way that they handle the threading for you. You write your code to be thread-safe and the container does the rest. It pools threads and assigns them one per request as they come in.
精彩评论