Servlet: Singleton, Singlethread or Multi Instance Multithread - java

This question has been asked previously and discussed before but i want to ask it further.
Are Servlets Singleton or not ?
According to me they are initialized only by the container but they are still not singleton ?? why ??
Are Servlets Single Thread or multi Threaded (Forget about javax.servlet.SingleThreadModel class)
i.e. What happens when there are multiple requests for a single servlet ??
If they are executed conncurrently, that means it is multi threaded ??
and if its multi threaded then each thread will have an instance of the servlet, which contradicts with the 1st point !!
What i think is,
Whenever theres a new request, The container creates a new Thread for the incoming Request say Req1, in that it calls or dispatches the control to the service method of servlet. Now this execution happens concurrenlty.. i guess so...
Does my working stands the same in a MVC envirionment ?? (say Struts 1/2, Springs)

The fact that exists just one instance doesn't means it isn't multithread. More thread can concurrently call tha same method of the same instance.
Servlets are absolutly multithread.

Servlets are multithreaded - this is the base for their efficiency.
One can use "implements SingleThreadModel" to make a servlet single-threaded, so for every request a new object will be created.
Recently this interface SingleThreadModel was deprecated

It depends on the implementation. The servlet interface doesn't specify.
http://docs.oracle.com/javaee/5/api/javax/servlet/Servlet.html
However, if you see the HttpServlet then you can see it specifies that it should be synchronized.
http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpServlet.html

Perhaps, the diagram given in the link below illustrates everything...
http://www.tutorialspoint.com/servlets/servlets-life-cycle.htm

Related

Thread safety in java web application?

What does someone mean when I am asked that whether my web application is thread safe or not , considering that I have not used Multiple threads in my webapplication.
In a normal web-application Servlet treats as Singleton class, it means if you are using instance variable in Servlet that is not thread safe in that case it will create an issue for multiple request that is served simultaneously.
A Java servlet container / web server is typically multithreaded. That means, that multiple requests to the same servlet may be executed at the same time. Therefore, you need to take concurrency into consideration when you implement your servlet.
Read more...
What does someone mean when I am asked that whether my web application is thread safe or not
You have to make sure that all the Servlet/JSP are thread-safe. Do it for all server side classes that is treated as Singleton.
I have not used Multiple threads in my webapplication.
Container/web server starts a new thread for each request.
The servlet specification requires a web application to be thread safe, because the servlet container may (and usually does) process requests concurrently. That is, even if you do not start any threads of your own, the servlet container will, and you must ensure your code is still correct in that case.
That involves protecting any objects shared by several threads (such as the contents of the HttpSession, or any singleton objects) from concurrent access.
An excellent answer to a similar question is witten by BalusC here. Also have a look at Tomasz's answer
Generally, instance variables or state can be shared across threads (threads created by application or the container). So any class(object) that exposes its state for modification, can be considered unsafe. So if your service layer calls some data access object method and the dao is an instance variable inside the service class, the question to ask is this - can this dao or the state of that dao itself be changed by some other client?
You can make your objects immutable. Your custom objects, dates and collections can be mutable. Some of the examples where even getter methods can be dangerous are collections, dates, etc. Use something like ConcurrentHashMap or return a list something like Collections.unmodifiablelist
Another example, instead of returning this.someDate, you should write
public Date getSomeDate() {
return new Date(someDate.getTime());
}
This way some other thread (which may have been spawned by container for another request from another user) holding a reference to the variable someDate will not be able to mess up with this thread.
If you cannot make the state of an object immutable because you want to allow its clients to change its state, you can make all the clients of that object agree to share the state. So if one thread changes the state of a shared object and another thread is ok with the state changed by the first thread, then such monostate object can be ok to have in your application.
As other answers have mentioned the container spawns threads even if your application does not. I have focused here mainly on the topics not directly covered in the answers here so as to avoid duplication. Hope this helps.

how to control a class(running/halting) from java servlet

I have a class which acts as a simple crawler and I want to invoke this class within a servlet.
My idea is to get an url from user then url request will be passed to the servlet and servelt pass the url to the class and class will start the crawling. and I want my servlet to create only one instance of this class.the retrieved data from crawlwer will be added to the DB directly by the class.
I want to control the behavior of the class like running/halting/stopping from servlet
(for this matter I think I am able to create a simple xml file which will be shared between servlet and class and if servlet change the status code class should response to the status change)
But I have some doubts about how to control the behavior of the class such as command it to run/halt/stop and since my class is not multithreaded I don't have any idea what will happen to invoked class after calling it from servlet and since this class needs to read from network obviously I'll have some gap/freezing phase during running it.
How can I solve the problem of concurrency in this situation?or in other word will I have any concurrency issue or not?
regards.
It depends on the Servlet container you are using. Some containers spawn a new Thread per user request (almost always this is the desired behavior), so you should definitely design for concurrency.
You can make the Servlet class implement SingleThreadModel, then in the service method you can directly call the crawler class code, as only a thread will enter service at a time.
This implies only an URL can be processed at a given time, which is probably not what you want, so instead of that, don't implement SingleThreadModel and create a singleton executor service in the init method:
ExecutorService ex = Executors.newFixedThreadPool(20); //Only 20 tasks at a given time
Then, in the service method create a new CrawlingTask (Runnable) with the URL specified in the request, then submit the task to the executor.
That way you could also shutdown it:
ex.shutdown();
As ExecutorService is thread-safe, you don't have to worry about concurrency when enqueuing tasks.
First, understand the difference between a Class and a Thread. A class is just code, a thread is where the code is executed. You don't stop/halt a class, you stop or halt a thread that is executing code in a class.
I would suggest you start reading up on Java concurrency programming. since what you are describing is very much about multithreading and thread synchronization.

How the servlets are shared among every request

How the servlets are shared among every request? I understand that each httprequest are allocated to different thread. How about concurrent request?
When you create your servlet you decide whether you will make it single threaded or multi-threaded. You can mark your servlet as single-threaded by implementing the interface
javax.servlet.SingleThreadModel
See this
A single threaded servlet can serve only one request at a time, and that's usually not what we want. So typically we allow our servlets to be multi-threaded and implement accordingly. Code on the assumption that many threads, each of which corresponds to one user's request, may be in our servlet at the same time. This is not hard to do - avoid using instance variables that can be changed by any one request thread and remember that any synchronized code will become a point of contention.
When a Servlet is requested for the first time or when the webapp starts up, the servlet container will create an instance of it and keep it in memory during webapp's lifetime. The same instance will be reused for every incoming request whose URL matches the servlet's URL pattern.
A separate thread is created to handle each HttpServlet Request.
See Servlet Tag Info for details.The info has links to great resources that would give you a better understanding of servlets.
I understand that each httprequest are allocat[ed] to different thread.
Correct.
How about concurrent request?
They are allocated to different threads.

Servlet Instance in the container

I knew only one servlet instance (One instance for one servlet basis) will be avilable in the web container. Is it possible to make a pool of instance in the web container ? Like a database connection? If i make a pool of servlet instance then how i can make that as a thread safe? (But i studied we can make only one servlet instance per servlet).
I understand that it was an interview question. I would have answered it as follows:
You can let the servlet implement SingleThreadModel to get the container to create a pool of multiple instances of the same servlet class. The maximum pool size depends on the container used, on Tomcat for example, this is 20. But, a big but, this interface is deprecated since Servlet 2.4! We should actually be writing servlets in a thread-safe manner, without assigning request- and/or session scoped data as an instance variable of the servlet. This way it's safe to use a single servlet instance across multiple threads (read: across multiple HTTP requests).
See also:
How do servlets work? Instantiation, sessions, shared variables and multithreading
Question is, why would you want to do that?
Servlet container instantiates single instance for each servlet declaration. That means, that you can have multiple servlet instances, but you need to declare the servlet as many times as many instances you want/need. This also brings the question of how servlets would be invoked ... they would need to be mapped to different paths.
Another way you can do this is to make a pool of handlers which your single servlet may call.
Re how to make them thread-safe: that depends on what exactly you want to do in those handlers. It's hard to tell you in general.
If you're asking about thread-safe pool, you can use Apache Commons Pool library, or some BlockingQueue (e.g. LinkedBlockingQueue) in Java: queue may contain your handlers. Servlet will take() first handler, use it, and put() it back after it's done. (This is just an example of course, there are many ways to implement pool).
But ... make sure you really need design like this, maybe your requirements can be satisfied by something simpler? (If your goal is to limit number of concurrent requests handled at the same time, maybe it's enough to just limit number of HTTP worker threads in your container? Or if that's not enough, you can use a limiting filter?)
Defining a pool of servlets does not make sense as the Servlet itself is not a thread. The Web Container (e.g. Tomcat) maintains a thread pool which calls the Servlet instance. So if you want to increase the throughput (concurrent users) you have to increase your web containers' pool size.

singletons and threads

My question is about threads being queued. For my example I have one Spring context. I have a method named CalculateTax in a stateless class. A request comes in, a thread is created (tA) and it eventually enters the CalculateTax method. Within the same "time frame" another request comes in and another thread is created (tB). Now, here is what I want to understand. AFAIK tB cannot execute CalculateTax until tA has exited the method. Is this true?
As long as CalculateTax only uses local variables (i.e. declared in the method), you will not have any thread sync issues and multiple threads can call the method without a problem.
However if for some reason CalculateTax uses variables defined at the class level, and you are using the Singleton pattern (you tagged your question with "singleton", so I guess you are), you may have thread sync issues.
No it is not true if they are parallel thread, each thread is in its own stack of execution so it should be able to execute while tA is executing.
This is what Threads are for.
Generally speaking the answer is undefined. If your 'request' comes from remote client the answer depends on implementation details of the mechanism used for service exposing.
However, I'm not aware about remote communication frameworks that really make the proxy serializing the requests, i.e. that is assumed to be addressed by target service developer (e.g. its your task to provide thread-safety for the service implementation OR serialize all requests using explicit synchronization etc).

Categories

Resources