thread in a webapplication (servlet, Spring , hibernate) - java

I understood the basic concept of Thread in standalone application. But, got confused in below areas.
1). In Java webapplication (servlet and Spring based)?
I hope, each request is handled by a different thread. Is this correct? Is there any other definition available?
2). what is a thread in Hibernate with Spring MVC?
Session factory is thread safe.. where as session object is not. What is mean by thread here?
Please help me to understand this.

1) The application server has a thread pool, when a request comes in it gets assigned a thread from the pool.The same thread calls the dispatcher servlet, which calls a controller, which calls a service, etc., and finally creates an HttpResponse and sends it to the client.
2) A usual pattern with Hibernate (if you're not using Seam conversations) is session-per-request:
2.4.2. Session-per-request pattern
This is the most common transaction pattern. The term request here
relates to the concept of a system that reacts to a series of requests
from a client/user. Web applications are a prime example of this type
of system, though certainly not the only one. At the beginning of
handling such a request, the application opens a Hibernate Session,
starts a transaction, performs all data related work, ends the
transaction and closes the Session. The crux of the pattern is the
one-to-one relationship between the transaction and the Session.
The transaction is stored by Spring in a threadlocal variable. So the thread has a Hibernate session (which is confined to that thread), and it is associated with a transaction (or a stack of transactions, since they can be nested).

Related

Spring request Thread closing

I'm using Spring Boot and every time, when I make request to my RestController, new Thread created. How can I close these threads explicitly? I mean, when something returned from my mapped method, Thread, in which it was executed, closes.
I know, that here is thread-pool in Tomcat, but I want do it all with my bare hands.
In Spring the controllers has a default singleton scope. So there is only one instance of the controller. The number of threads is controlled by the number of instances of dispatcher servlet. You can see how to configure that number in the Spring MVC tutorial.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html
And here how to manage thread safe
https://studiofreya.com/2012/02/06/spring-mvc-how-to-build-a-thread-safe-controller/

EJB Service Locator with caching

I am using a Service Locator implementation which caches the result of javax.naming.Context#lookup call, and maps it to the requested EJB interface, so all subsequent requests (for the same EJB) after the first one, return the cached instance.
My concerns are:
Since the same instance is used, there is no utilization of the
server EJB pool which would serve multiple simultaneous requests
with multiple EJBs (unless the underlying server logic somehow makes
use of the EJB pooling)
Stateless and stateful EJBs are thread safe, but since, again,
only one instance per EJB class is used, and EJB has EntityManager
injected via #PersistenceContext, I assume that means that multiple
threads could be using the same EntityManager instance (not just the
persistence context), which definitely is not thread-safe
Do you think that it's best not to use caching in the Service Locator, or that my concerns are unjustified regarding EJB behavior?
What you get from the lookup operation (through the JNDI service) is an object called Stub and him is not fixed with any special EJB instance.
Once cached, every time you invoke an EJB service the stub is able to select a different EJB instance from the pool (this apply to stateless); even in a cluster environment, the stub object is able to select an EJB instance from different servers.
Therefore, caching the stub object should not be a problem.
Notice that I'm talking about stateless, I think that caching doesn't make sense to statefull session bean.
The EJB lookup is a time-consuming operation, so caching improves the client performance.
About your comment:
If you were using EntityManager inside a component that is used by multiple concurrent threads like a Servlet, yes, you will have to care about concurrency, but the EJB's Tread Model imply that will not be several thread using the same EntityManager instance at the same time, so the fact that EM is not thread safe doesn't matter.
What concerns me still is the fact that different EJBs are using the
same injected (via #PersistenceContext) EntityManager instance
I think that for simple sceneries the best way to think about it, if as describe here:
The most common pattern in a multi-user client/server application is
entitymanager-per-request. In this model, a request from the client is
send to the server (where the JPA persistence layer runs), a new
EntityManager is opened, and all database operations are executed in
this unit of work. Once the work has been completed (and the response
for the client has been prepared), the persistence context is flushed
and closed, as well as the entity manager object.
This will be more difficult to check ;)

Accessing servlet scoped beans from another thread

I am using approach from the "Accessing scoped proxy beans within Threads of" answer. However I am seeing rare deadlocks involving RequestAttributes object. The main reason of the deadlock is between the synchronized (this.sessionAttributesToUpdate) statement in the object and servlet session hash-map. Normally the instances of the object are created for each request, so they don't clash, but if I pass the object to another thread to use the session beans, the same object is used and it causes deadlock sometimes.
The deadlock happens if current http request is not completed while the another thread starts using a session bean passed with RequestContextHolder.setRequestAttributes.
I think this guy mentions the same problem, but his question is unanswered: Session scoped bean encountering deadlock.
So, any ideas how to avoid the deadlock?
Here's an answer that provides alternative solution considering the objective is to calculate something in background while user is navigating pages.
Possibility 1:
Create a service bean with processing method that is annotated with #Async (http://static.springsource.org/spring/docs/3.0.x/reference/scheduling.html) that returns a result of computation in a Future object. Store the Future object in the session. Access the result in subsequent requests through Future object if task is completed. Cancel the the task via Future.cancel if session is to be destroyed before task is completed.
Possibility 2:
Take a look if new features of Spring 3.2 and Servlet 3.0 async processing can help you:
http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-async
Possibility 3:
Emulate a task queue. Create a singleton service that can put objects to structure like ConcurrentMap where key would be some job id (you can than store key into session) and value the result of background processing. Background thread would then store objects there (this is perhaps not much better than accessing session directly, but you can make sure it's thread safe).

Does a session-scoped backing bean have to be implemented thread-safe?

Is it possible, that a session-scoped backing bean is accessed by multiple threads at the same time?
The servlet spec says, it is possible:
Multiple servlets executing request threads may have active access to the same
session object at the same time. The container must ensure that manipulation of
internal data structures representing the session attributes is performed in a thread
safe manner. The Developer has the responsibility for thread safe access to the
attribute objects themselves. This will protect the attribute collection inside the
HttpSession object from concurrent access, eliminating the opportunity for an
application to cause that collection to become corrupted.
However I could not make the server (JBoss) use different threads for the same session. When I opened multiple tabs and started a long running request in one tab, and then started a request in another tab, the second tab had to wait for a response until the action started in the first tab was completed.
I also verified this by blocking the thread with a breakpoint in the backing bean. It was not possible to do anything in other tabs of the same session until I resumed the thread.
Despite this we have some strange exceptions in the production log and so far the only possible explanation we have is, that multiple threads concurrently access the same session-scoped backing bean.
Yes, A Servlet session is thread safe. But, if you are putting mutable object in the session. The application should take care of the synchronization.
In your case, if your Bean is Mutable i.e, has state. Yes it has to be thread safe.
And about your test case, it depends on the browser you are using. Most browsers support upto 6 connections in parallel for every server. But, Not sure if they use parallel connections if there have cookies.

Spawning new java threads with in Message Driven Bean ( MDB)

Can I start /spawn new java thread from within a MDB?
I have a requirement to do some parallel processing from code in MDB and then return the control back to MDB.
Requirement:
Message come to MDB , then some processing of code. Then two new slave thread are started which do some parallel work. Till then MDB is waiting. when threads finish the work. Then control is returned back to MDB, which completes the the related final/cleanup work.
Is it good idea to start a new thread ( Runnable) from MDB? If not then what should be the alternative?
It is a bad idea, if you are performing transactional work in the threads.
A thread that is currently performing work in a transaction started by the EJB container, is associated with a transaction context. In your case, the onMessage method in the MDB initiates a new transaction (unless you have specified a NotSupported descriptor), and the thread performing this transaction would be associated with a transaction context. Starting a new thread, does not propagate the transaction context to the child thread. This would result in a new transaction being created when the container detects that the child thread is attempting to access a transactional resource without a transaction context.
Although some (or most?) transaction managers support the presence of multiple threads possessing the same transaction context, this might (and most likely will) not apply to application initiated threads.
Starting new threads with in MDB is bad practice. It will work but the new threads are not in control of application container so can behave unpredictably. They can even mess-up the thread management which container is trying to maintain. Worst affect is if the application is deployed in cluster then user defined threads will fail miserably.
In your scenario : Instead of starting new threads , create new MDB with logic of thread ( This way it will be managed by contaner now) then send message to these new MDB. If you want the control back to parent MDB then, I think , use your parent MDB in global transactional so that parent MDB will wait for child MDB to finish and control will return back.
Starting a thread from an MDB violates the specification.
Enterprise JavaBeansTM,Version 3.0, EJB Core Contracts and Requirements states in section 21.1.2 Programming Restrictions:
An enterprise bean must not use thread synchronization primitives to synchronize execution of multiple instances.
The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt
to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups.
You are fundamentally missing the point of Java EE and MDBs.
A Java EE container is a managed runtime environment. The principle idea behind the Java EE container is that by delegating certain orthogonal concerns, such as transaction management, to the container, the component remains focused on business logic and (in utopia) be a reusable component that makes little assumption about its runtime environment.
Prior to MDBs, the Java EE container was a passive-reactive system that allowed no means for coordinating the action of a container side asynchronous active agents. Message Driven Beans then addressed this, providing a standard way for you to kick off an asynchronous action, server side.
You have an original event e0 which is consumed by MBD0. On message, MDB0 will generate e1 and queue a message in response to MBD1, which will then do its work and send msg to MDB2, etc.
There you have a simple workflow of n sequential steps using pub/sub messaging semantics (and o/c with asynchronous semantics), and all threads involved are managed by the container. If you wish to have concurrent actors working and then collecting results and kicking off a final action, consider using patterns involving JMS topics.

Categories

Resources