How Multi-User Java Applications Really Work - java

This question is rather broad I'm sure but I believe I don't fully understand how multi-user applications work and I would like some clarification on the subject or an idea of where to look for more info (not sure I know what to search for)
I understand the development aspect, but once you deploy the code to the server, how does it handle multiple users? For example, if I have a singleton class then that class will only ever be instantiated on the server once ... but the class will need to be used by multiple users simultaneously which means that the variables inside the class need to potentially be different for each user, how is this achieved behind the scenes?
Is it just the concept that each different user will access the class on a different thread? and if so, wouldn't that mean the whole application needed to be thread safe?

Let me explain this straight and will start from this point
once you deploy the code to the server, how does it handle multiple users?
----> Yes every web application or enterprise application should be deployed in server, web application on web server like tomcat enterprise applications on WebSphere. Every server will have servlet container with multiple number of threads (by default 200 in tomcat) each input request will be handled by individual thread (so multiple request can execute concurrently)
if I have a singleton class then that class will only ever be instantiated on the server once
---> yes singleton class will have only one instance per server, so multiple threads can access same object concurrently and which may cause data inconsistency, which is developer responsibility to take care of this responsibilities. The main problem with singleton class will be class (instance or static) level variables with setter methods because two threads can access same object concurrently and change the values, In the real time scenario singleton design pattern is used for Connection Pool object
Note Local variables are best in multithreading because every thread has its own stack, and they cannot be access by any other threads.
but the class will need to be used by multiple users simultaneously which means that the variables inside the class need to potentially be different for each user
---> To save request properties into object Models or POJO will comes into picture, these are prototype for every request new object will be created.

Related

Singleton Scope in a server

We have a Application server which runs a service and it is being invoked from web page. If there is a singleton object in the service, Will it be shared across all the instances of pages (for each service call)?
It depends how your singleton is implemented. In general (on a clean software design) the singleton runs during the runtime of your program. A web server is a program running in the background. If the singleton runs inside of this program than the singleton object will live over all instances of pages. If your Web server starts an other (java-)program otherwise.
Yes. The GoF Singleton pattern ensures that one and only one instance of a particular class is created per ClassLoader.

How is multi-threading different in a Java based Web Application vs Stand-alone Java Application

I am fairly new to Java and my experience is limited to Web Based Applications running on a Web Container (Jboss in my case).
Am I correct in saying that for Web Applications the web container takes care of multi-threading? If so, can I introduce new treads in a Web Based applications? Is there any advantage in doing so and in what scenario one would need to do that?
Thanks
Most web containers make application they run multi-threaded, since containers implement 'multi-threaded servlet model'. So, your application (code of your servlets) already being run by several threads, therefore, it must be thread-safe (you must use proper synchronization when accessing shared data, such as your servlet class' instance fields, etc.)
It's perfectly legal to launch new threads from within your web applications. For example, you may need it to launch some long-running task (registration of user in database which ends in email sending, or calculation of PI up to 100000th decimal place) and close user HTTP request immediately after that, making user's browser finish loading given URL.
The web application server tends to create a new thread for each request. As such if two suers are filling the form and submitting it at the same time, you can be rest assured that both request are sent to the server using separate threads. The number of concurrent users accessing any particular page will actually determine the load the page can handle.
As far as creating new threads are concerned. You can certainly create new threads inside the application using the conventional java methods to create a new thread.
Generally you would like to create a new thread in case you want to perform an async task and does not want the user to wait for the output. Say suppose insertion of large data in DB which is nowhere related to user will generally be written in thread.
Also, in case where you intend to perform long running task in the background, the code is generally written inside a thread.
At times, there are requirement that the user accessing the page and requesting for something also needs to be inside a thread at your server end. E.g. trying to access a printer. IN that case you also need to ensure that your code is written inside a thread and you have properly synchronized the method.
Am I correct in saying that for Web Applications the web container takes care of multi-threading?
Most of the Severs are multithreaded to handle multiple request concurrently.
can I introduce new treads in a Web Based applications?
Yes you can. It depends on your requirement .
Is there any advantage in doing so and in what scenario one would need to do that?
If there is a time taking job which can be done asynchronously in to parts then use multiple threads.
e.g. on a request you have to read a huge file and dump in to database. In such case you can use multiple threads to read line by line and insert in to DB.
As I said it depends.
Most web application servers handle incoming requests on their own thread. That means if your server handles 5 requests concurrently it's running 5 threads.
That's usually enough multithreading to sufficiently exercise a medium-to-big server.
If, however, you've got an atypical workload (for example few requests, but each requests includes heavy computation), then introducing your own multi-threading on top of this may be worth the investment.

Singleton use in different thread

I have a remote service and an, object (singleton). When I call the singleton class from UI thread and remote service I get 2 objects. Can anyone help me?
If you have a remote service then you have 2 completely separate processes. Each process has its own virtual machine. Therefore, your singleton class is instantiated once in each process.
If you really need a single then think about whether you really need a remote service. If you can implement your remote service as a local service then that will solve your problem.
If, on the other hand, you really need a single instance that is shared across the 2 separate processes, then you will need to instantiate the singleton only in the remote services process and access it via remote calls from the UI process.

ThreadLocal safety in Weblogic threadpool

I'm writing an app which uses MDBs, EJBs and needs ThreadLocal to pass and log a variable across multiple EJBs and Helper classes until the transaction is complete.
The flow is
Starting with MDB onMessage()
-> some business delegate EJBs
-> some helpers
Question:
This app runs within Weblogic and Weblogic re-uses Threads from within it's ThreadPool. So is there a possibility of data corruption across threads? Is the solution to use ThreadLocal.remove() safe enough?
Is there an alternative to ThreadLocal other than passing around the Object as a parameter to all methods?
WebLogic does not reset user set ThreadLocal variables when the thread is returned back to the pool - the user is responsible for managing them. When such threads are reused, its likely they will interfere. You may run into memory leaks since the thread local reference isn't cleaned up. You can safely reset your thread locals prior to returning the thread back to the container. The ThreadLocal.remove() call should clean it up (ensure that its done in a finally block)
Note that if any async or rmi calls are involved, your thread locals will not propagate. You may want to consider the WebLogic WorkArea feature which allows context propagation across threads, clients & servers. More details can be found at http://download.oracle.com/docs/cd/E17904_01/web.1111/e13706/context.htm#i1058690
You can't reliably use a ThreadLocal in the EJB tier. Even if your code seems to 'work' now, what happens if someone deploys one of your beans remotely? From EJB Restrictions:
Why is thread creation and management disallowed?
The EJB specification assigns to the EJB container the responsibility
for managing threads. Allowing enterprise bean instances to create and
manage threads would interfere with the container's ability to control
its components' lifecycle. Thread management is not a business
function, it is an implementation detail, and is typically complicated
and platform-specific. Letting the container manage threads relieves
the enterprise bean developer of dealing with threading issues.
Multithreaded applications are still possible, but control of
multithreading is located in the container, not in the enterprise
bean.
If you need to share state, you should pass it in to the EJB method as a parameter. Is there a reason this approach won't work for you? Another option would be to temporarily dump it into a transaction enlisted database or cache.
#JoseK: though I have not tried what you described in your issue, but here are my thoughts:-
Both MDB and Session beans are thread-safe. It means let us say if there is pool of 10 beans, only 10 requests will be handled simultaneously. Other requests would be queued for their turn. So one running thread local data should not interfere with other thread.
If you confident to use always local EJBs in future also, then I don't really see any issue in using thread local data. Because you are not really creating threads.
Though weblogic provides thread from thread-pool but that thread is given dedicately to each request flow, I don't think its local data should become corrupted ever.
As I said I have not tried myself, what I would try is:-
In MDB layer(your first layer), do Thread.getCurrentThread.setName(name)
and in subsequent layers print thread names like Thread.getCurrentThread.getName)
Perform multiple runs with different size of ejb pool, thread pool. Give a different thread name to each request flow. Try running multiple requests same time. And see if you ever get thread name mixed.
5.Having said above, to keep things simpler and furture remote EJB support, I would also pass CallingContext Interface to each layer.

Thread Local recommendations in heavy back-end mid-tier server application

Is it recommended to use ThreadLocal to store a Thread Context?
I am building a backend server application where there are typical services that I need to run.
Note: We are not building this over a SOA architecture.
Before the start of each service I need to give it a state which has some Service Contex which is variable map to work up on. This variable map is shared when services are running parallelly.
Now for example a service needs to check weather it has to be halted or timed-out based on some thread related parameters.
Question: Is it a good approach to keep the thread context inside thread local and then building api's over service context to access parameters over these variables.
This would help me to hide the complex behavior and it wouldn't open up my internal things.
Thanks,
Aditya
It looks like your server application framework ought to provide you with the means to implement this functionality in a simpler way - unless you are implementing your own framework.
Now for example a service needs to check weather it has to be halted or timed-out based on some thread related parameters.
An EJB container provides this kind of functionality. EJBs also provides a session context and the means to ensure that the context can be restored if execution is transferred between threads (by passivation + activation).
You can use ThreadLocal quite freely but you must define your thread model cleanly (see if you have any control on the thread creation)... also keep in mind that assuring the state stored in the ThreadLocal might not what you expect, if you are relying on any clean-up code.
Also: do use (cant stress more) WeakReference for anything that your code is not directly responsible.

Categories