I am currently studying concurrency for javascjp exam and I have some confusion as to the underlying purpose of threads. This may be due to my background. I am hoping that someone can clear this up so that a lightbulb may become dimly light.
Currently, I code java code for a website that utilizes the Struts framework. Whenever the code is written, it is done so in a flow for a particular user. I assume that once a user hits our site, they have a session started. As they proceed through the various functionality, the session is what ties the user to the various code instances that they create. All of this runs on a weblogic application server.
We do not code with threads,....but if we were to code with threads, would the multiple threads within the application still be tied to a particular users session? I guess some of the confusion also stems from the thought that as hundreds of users are accessing the website, they are given their own threads to complete the required functionality they call, or is this just an absurb assumption on my part? It seems hard to believe that threads can be used in a web application. Can anyone shed a little light on this? Thanks.
Each request to the server becomes a separate thread. That is why it is important that each Servlet is thread safe. You might have several users in the same object at the same time. Don't forget that the only things your servlet classes know about the session is what it gleans from parameters passed to it when its methods are called.
However, there is no reason that you cannot spin off additional threads. You have the responsibility of coordinating the threads.
An example of how we use threads is when some events occur, we have to notify several people via e-mail and voice message. We spin off threads to manage that process because the user does not need to know about or wait for those actions to occur. If we wanted to we could tie them to the session by passing the parameters such as HttpServletRequest to the threads when we spin them off.
Does that help? Les [ November 14, 2007: Message edited by: Les Hayden ]
As already mentioned, your servlet container is already creating a new thread for each request, so you're already working in a multi-threaded environment. While the servlet framework hides the details of thread creation from you, all the servlets you write for a given web app must still take appropriate precautions to ensure thread safety.
Also, if you're writing a rich client application, you'll find that many GUI frameworks also use threads to implement event notifications. For example, when the user clicks a button, the framework may invoke each mouse click listener object's callback method in a separate thread. This generally helps to keep the UI responsive, among other benefits. Long-running computations should also usually be run in their own threads, for similar reasons.