What happen even many request comes through one spring controller?
Does Spring pipe it?
How about add #Transactinal on controller?
Is it have a benefit to use on controller layer?
Basically you are asking 2 questions
How are multiple, concurrent, requests handled by a handler.
Should we add #Transactional to a handler.
Multiple concurrent requests are handled concurrently. Each thread has its own callstack and location in memory and doesn't share a thing. In general no problem (used Spring MVC in very high concurrent applications) unless you start, for some reason, sharing state in your singleton, or forget to clean-up ThreadLocals.
Adding #Transactional is something bad, IMHO. The transactional layer is NOT your web but your service layer. So don't add transactions to your web but add them to your service layer.
Related
Is there any way to make use of Java EE Asynchronous Web Servlet processing in Spring Web Flow? I see a fair amount about Spring MVC support, but nothing about Web Flow. Where ideally I'd want only certain transitions or actions to use the approach.
Would you have to use the DeferredResult approach? Although that seems to be intended for doing the work somewhere unaware of the web container context, which Web Flow isn't.
I can get the native HttpServletRequest, of course, and from there call:
AsyncContext acontext = startAsync();
But since Web Flow isn't dealing with low level HTTP request/response objects, I don't know how I'd tie the two together.
I'd love to see a working example. I'm hoping I don't have to exit Web Flow in order to do the Asynchronous request processing.
Earlier days when I used to do coding, I used mostly Stateless Session Beans and all the info needed to traverse across pages was put in HTTP Session object. Back then(and even now) I never understood the "USP" of EJB being "transparent" and "safe" for "business layer" implementation with its round about ways of dealing with Skeleton and Stub and other jargons which were an overkill masquerading in the name of ease of use/secure. I was just wondering why exactly one would have used Stateful Session EJB, if the same can be accomplished via a SLSB + HTTPSession? Please dont give me the high level example of Shopping cart or bank app, as I already know that. I am looking for some answer that would be detailed on why coders chose SFSB over SLSB+HttpSession. Plus how are these session related stuff handled in your experience recently?
You are supposing that the view layer always is a http client. But the view layer can be architected in other ways.
For example a Java Swing client application (Where the client server communication is done only with ejbs.
A question that helps diff SFSB vs HttpSession.
Stateful Session Bean and HTTP Session
I have a WCF service with ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple). I want to use ThreadStatic variable to srore data.
I start worrying about is it possible two parallel requests for the same or different operationContracts get handled by the same thread serverside, because if this happens my ThreadStatic variable will get overriden.(I.e. something like the thread changing between HttpHandlers and HttpModules in ASP.NET)
I made a spike service with the same ServiceBehaviour and maxConcurrentCalls="2". After that a wcf client called the service with 50 parallel requests and my worry did not occur. However this is not a 100% proof.
Thank in advance!
Irrespective of the ConcurrencyMode, a ThreadStatic value will persist when your request terminates and the thread is returned to the thread pool. The same thread can be reused for a subsequent request, which will therefore be able to see your ThreadStatic value.
Obviously this won't be true for two concurrent requests, because by definition they will be executed on different threads.
From comments:
Also by definition MSDN says: 'The service instance is multi-threaded. No synchronization guarantees are made. Because other threads can change your service object at any time, you must handle synchronization and state consistency at all times.' So it is not so obvious:)
This means that a single instance of your service class can be accessed concurrently by multiple requests. So you would need to handle synchronization for any accesses to instance members of the service class.
However ThreadStatic members are by definition only used by one thread (and hence one request) at a time, so don't need synchronization.
The direct answer to your question is Joe's answer.
However you mention in the comments you are using an ambient design pattern. That pattern is already implemented in WCF as the OperationContext and is specifically designed to be extensible. I highly recommend using OperationContext over any custom thread storage.
See Where to store data for current WCF call? Is ThreadStatic safe?
I wanted to add to Joe's answer here because I would recommend that you use some sort of correlation for your requests if you're needing to store state. The threading model will become very convoluted and unreliable in production.
Further, now imagine you have two IIS servers hosting this service and a hardware or software load balancer forward facing so that you can consume it. To ensure that the correct state is gathered you'll need correlation because you never know which server the service will be started on. In the post below I mocked up a simplified version of how that might work. One thing to keep in mind is that the SessionState would need to be kept in a shared location to all instances of the service, an AppFabric Cache server for example.
Global Variable between two WCF Methods
This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Closed 6 years ago.
I need to know why the servlets are not thread safe ? And whats the reason that in Struts 2.0 framework controller servlet is thread safe ?
I need to know why the servlets are not thread safe ?
Servlet instances are inherently not thread safe because of the multi threaded nature of the Java programming language in general. The Java Virtual Machine supports executing the same code by multiple threads. This is a great performance benefit on machines which have multiple processors. This also allows the same code to be executed by multiple concurrent users without blocking each other.
Imagine a server with 4 processors wherein a normal servlet can handle 1000 requests per second. If that servlet were threadsafe, then the web application would act like as if it runs on a server with 1 processor wherein the servlet can handle only 250 requests per second (okay, it's not exactly like that, but you got the idea).
If you encounter threadsafety issues when using servlets, then it is your fault, not Java's nor Servlet's fault. You'd need to fix the servlet code as such that request or session scoped data is never assigned as an instance variable of the servlet. For an in-depth explanation, see also How do servlets work? Instantiation, sessions, shared variables and multithreading.
And whats the reason that in Struts 2.0 framework controller servlet is thread safe ?
It is not thread safe. You're confusing the Struts dispatcher servlet filter with Struts actions. The struts actions are re-created on every single request. So every single request has its own instance of the request scoped Struts action. The Struts dispatcher servlet filter does not store them as its own instance variable. Instead, it stores it as an attribute of the HttpServletRequest.
Servlets are normal java classes and thus are NOT Thread Safe.
But that said, Java classes are Thread safe if you do not have instance variables. Only instance variables need to synchronize. (Instance variable are variables declared in the class and not in within its methods.
Variables declared in the methods are thread safe as each thread creates it own Program Stack and function variables are allocated in the stack. This means that variable in a methods are created for each thread, hence does not have any thread sync issues associated.
Method variables are thread-safe, class variables are not.
There is a single instance of a servlet per servlet mapping; all instance properties are shared between all requests. Access to those properties must take that in to account.
Struts 2 actions (not "controller servlet", they're neither servlets nor controllers) are instantiated per-request. Action properties will be accessed only by a single request's thread.
Servlets are normally multi-threaded.
Servlet containers usually manage concurrent requests by creating a new Java thread for each request. The new thread is given an object reference to the requested servlet, which issues the response through the same thread. This is why it is important to design for concurrency when you write a servlet, because multiple requests may be handled by the same servlet instance.
The way that servlet containers handle servlet requests is implementation dependent; they may use a single servlet, they may use servlet pooling, it depends on the vendor's system architecture.
Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues.
Servlet is not thread safe but we can make it as a thread safe by implementing that servlet class to SingleThreadModel
like the given below class definition but again the performance problem will be there so better option would be use synchronized portion
public class SurveyServlet extends HttpServlet
implements SingleThreadModel
{
servlet code here..
...
}
Servlet is not thread-safe by itself. You can make it thread-safe by making the service method synchronized.
you need to implement SingleThreadInterface to make it thread-safe.
Normally Servlets are initiated just once and web container simple spawns a new thread for every user request. Let's say if I create my own web container from scratch and instead of Threads, I simply create Servlets as Singleton. Will I be missing anything here? I guess, in this case, the singleton can only service one user request at a time and not multiple.
Normally Servlets are initiated just once and web container simple spawns a new thread for every user request.
The first statement is true, but the second actually not. Normally, threads are been created once during applications startup and kept in a thread pool. When a thread has finished its request-response processing job, it will be returned to the pool. That's also why using ThreadLocal in a servletcontainer must be taken with high care.
Let's say if I create my own web container from scratch and instead of Threads, I simply create Servlets as Singleton. Will I be missing anything here?
They does not necessarily need to follow the singleton pattern. Just create only one instance of them during application's startup and keep them in memory throughout application's lifetime and just let all threads access the same instance.
I guess, in this case, the singleton can only service one user request at a time and not multiple.
This is not true. This will only happen when you synchronize the access to the singleton's methods on an application-wide lock. For example by adding the synchronized modifier to the method of your servlet or a synchronized(this) in the manager's method who is delegating the requests to the servlets.
JavaEE used to have a mechanism for this - a marker interface called SingleThreadModel that your servlet could implement:
Ensures that servlets handle only one request at a time. This interface has no methods.
If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method. The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each new request to a free servlet.
Note that SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used. It is recommended that a developer take other means to resolve those issues instead of implementing this interface, such as avoiding the usage of an instance variable or synchronizing the block of the code accessing those resources. This interface is deprecated in Servlet API version 2.4.
Containers could use this to instantiate a new servlet for each request, or maintain a pool of them, if they chose to.
This was deprecated in Servlet 2.4, for the reasons documented above. Those same reasons still apply to your question.
That's basically it.
I would question the motivations for creating your own container, with so many available for a wide range of purposes.