using static classes in servlets - java

Servlets are not thread safe. So if I use a static function of a class, What will happen when multiple requests come at the same time. How will they deal with the static function?

You'll have to synchronize it if accesses shared, mutable data. If the data is immutable or read-only or on the stack you should be fine.

It depends on what kind of static method do you have whether it is stateless or not. If it is stateless, and not referencing anything outside from your method's scope it will be thread safe.

if you are using static method in servlets you need to make them thread safe by
Using only local variables when state of the variable may change
or use static variable if they dont change or use synchronize access method
and you can amke function thread safe by implementing the SingleThreadModle interface or by 'synchronize' construct.

Related

Does my elasticsearch callee method needs to be threadsafe?

I am using RestHighLevelClient provided in elastic search java library. As per documentation, this class is threadsafe. I am using create index function inside a method. Do I need to specifically made that thread safe?
Or in general, if the objects used by a java method are threadsafe, then does it make sense to make method thread safe?
Do I need to specifically made that thread safe?
Since you seem to mean making the method synchronized, the answer is no. "Thread-safe" means that the methods of the class can be safely invoked from multiple threads without external synchronization like the one you propose.

What is the use of ThreadLocal?

What is the use of ThreadLocal when a Thread normally works on variable keeping it in its local cache ?
Which means thread1 do not know the value of same var in thread2 even if no ThreadLocal is used .
With multiple threads, although you have to do work to make sure you read the "most recent" value of a variable, you expect there to be effectively one variable per instance (assuming we're talking about instance fields here). You might read an out of date value unless you're careful, but basically you've got one variable.
With ThreadLocal, you're explicitly wanting to have one value per thread that reads the variable. That's typically for the sake of context. For example, a web server with some authentication layer might set a thread-local variable early in request handling so that any code within the execution of that request can access the authentication details, without needing any explicit reference to a context object. So long as all the handling is done on the one thread, and that's the only thing that thread does, you're fine.
A thread doesn't have to keep variables in its local cache -- it's just that it's allowed to, unless you tell it otherwise.
So:
If you want to force a thread to share its state with other threads, you have to use synchronization of some sort (including synchronized blocks, volatile variables, etc).
If you want to prevent a thread from sharing its state with other threads, you have to use ThreadLocal (assuming the object that holds the variable is known to multiple threads -- if it's not, then everything is thread-local anyway!).
It's kind of a global variable for the thread itself, so that any code running in the thread can access it directly. (A "really" global variable can be accessed by any code running in the "process"; we could call it ProcessLocal:)
Is global variable bad? Maybe; it should be avoided if we can. But sometimes we have no choice, we cannot pass the object through method parameters, and ThreadLocal proves to be useful in many designs without causing too much trouble.
Use of ThreadLocal is when an object is not thread-safe, but you want to avoid synchronizing access. So each thread stores data on its own Thread local storage memory. By default, data is shared between threads.

How threadlocal variable is different from a method level variable

If I use a threadlocal variable, then each thread gets a local copy of the variable. My first question is, if each thread mutates the variable, will the mutated value stay in its local copy only? Or at some point will it try to update the 'global variable' too and we will run into concurrency issues?
My other question is: if I declare a variable in a method, then each thread executing the method in its own stack will get its own copy. So is declaring a method level variable the same as making it threadlocal?
First question: each thread updates its copy of threadlocal variable, no global state is shared between threads.
Second question: if you declare local variable it behaves similary to threadlocal - every thread has its own copy but you don't have global access to it e.g. in another method - that's when threadlocal is useful.
The easiest way to look at a ThreadLocal<T> object is as a Map<Thread, T>, where the ThreadLocal#get() call would lookup the proper value by calling Map#get(Thread.currentThread()) on the underlying Map. Note that this is not the actual implementation, but the easiest way to look at it.
ThreadLocal variables are only useful as a member that can actually be accessed by multiple threads at the same time. Local declarations of a variable in a method are just that, local, and therefore not accessible to other threads. I would not say they are 'the same', but that they are both threadsafe.
Typical usage would be an instance member variable of a singleton object, or a static member variable of a class, in a multi-threaded environment.
Mostly, you will see them used to pass around request context information in a servlet environment.
If i use a threadlocal variable, then each thread gets a local copy of
the variable
I think there is some cunfusion regarding the term local copy of the variable. There is no copy. Every thread gets its own variable; these are independant of each other. It doesn't mean, however, that they cannot hold a reference to a shared object. So, just using threadlocal variables alone does not save you from concurrency issues.
Regarding your second question: No. Local variables and threadlocal variables are different. Local variables are not accessible outside the block in which they are defined. Therefore, for example, calling the same method twice will result in a different value each time. On the other hand, threadlocal variables keep their values as long as the thread exists.
Basically, threadlocal variables are kind of 'static' variables for one single thread.
An important point about ThreadLocal variable is the global access. It can be accessed from anywhere inside the thread.inside any method which calls in that thread context.
If you want to maintain a single instance of a variable for all instances of a class, you will use static-class member variables to do it. If you want to maintain an instance of a variable on a per-thread basis, you'll use thread-local variables. ThreadLocal variables are different from normal variables in that each thread has its own individually initialized instance of the variable, which it accesses via get() or set() methods.
Let's say you're developing a multithreaded code tracer whose goal is to uniquely identify each thread's path through your code. The challenge is that you need to coordinate multiple methods in multiple classes across multiple threads. Without ThreadLocal, this would be a complex problem. When a thread started executing, it would need to generate a unique token to identify it in the tracer and then pass that unique token to each method in the trace.
With ThreadLocal, things are simpler. The thread initializes the thread-local variable at the start of execution and then accesses it from each method in each class, with assurance that the variable will only host trace information for the currently executing thread. When it's done executing, the thread can pass its thread-specific trace to a management object responsible for maintaining all traces.
Using ThreadLocal makes sense when you need to store variable instances on a per-thread basis.

ThreadLocal Vs Cloning

I have been reading about threadlocal and scenarios where it is useful.
I like the concept but was wondering how is it different from cloning?
So a threadlocal will return a new copy of a variable which means that we donot have to use synchronization. A good example is SimpleDateFormat object which is not thread safe and ThreadLocal provides a good way to use.
But why can't we simply create a new copy of varibale use clone ?
What is the value add provided by ThreadLocal class as compared to cloning?
ThreadLocal is not a replacement for synchronization or thread-safe object access. If the same object is assigned to a ThreadLocal from different threads, then the program is no more thread-safe than it was before: the same object will still be shared among the different threads.
ThreadLocal acts-like a variable; that is, it "names" or "refers to" an object:
[ThreadLocal] provides thread-local variables [.. such that] each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable.
That is, what ThreadLocal does is it provides get/set isolation between threads that use the same ThreadLocal object. So each thread could assign/retrieve its own different object to the ThreadLocal; but this would still require a "clone" or new instantiation to assign the different objects to begin with!
Remember, an assignment (or method invocation) never creates an implicit clone/copy/duplicate of an object - and this extends to ThreadLocal.
By using ThreadLocal you create as many variables as there are threads, without the need for any further checking. Remember however, that the storage itself does not guarantee thread-safety. You must make sure that each object stored in local storage is used only from that thread!
Should you clone objects manually, you would have to clone an object every time it is used, or check in which thread we are and then clone.
Besides - is cloning operation thread-safe? What would happen if two different threads attempted to clone an object? I actually do not know, but I think that it would not be good practice.
Using ThreadLocal is faster, the SimpleDateFormat instance stored in a ThreadLocal can be reused multiple times in the same thread, while cloning means creating a new object every time.

Question regarding multi-threaded environment of servlet

If there is a servlet, inside a servlet container such as Websphere. The servlet are executed by some threads. I would like to ask, what does the threads share? How variables are shared between them?
Do they have a local copy of the following variables?
1) private/protected/public final Semaphore permits = new Semaphore(50);
2) private/protected/public final static Semaphore permits = new Semaphore(50);
3) private/protected/public Semaphore permits = new Semaphore(50);
4) private/protected/public static Semaphore permits = new Semaphore(50);
How should I declare the semaphore so that I can use semaphore to control them? I don't want them to have each of them a copy of the semaphore. Thanks.
Threads are run by Websphere thread pool and you should not be concerned about accessing them or sharing information via them.
Your semaphore will be shared if you declare it static in your servlet, for as long as all classes that use it live in the same application under the same classloader. However, there is a big risk in this case that if your execution path does not release permit (for example due to exception) you may end up with all threads blocked.
Each thread has its own stack, but all share the same memory space. With that in mind, a single instance can be shared, and so its state/properties, among multiple threads. Hence, we need to take care of state using synchronisation or similar techniques.
If you define a static variable or a single instance of servlet will be used -- which is highly likely but no guarantee, then it would be the same for all threads.
Nonetheless, you should create a class which provide a singleton semaphore to be used in servlet. That way servlet instances will be using the one and the same semaphore object, no matter what.
If you want to share a semaphore, it must be created by one thread, then handed out to the others (via some form of (possibly static) getter method) when they need it.
If you create the Semaphore object in each object, they'll all have different ones, defeating the purpose.
Servlets must be thread safe. This means your servlets should be "stateless" (unless you really know what you're doing). Essentially, use only local variables - not fields.
If you want to share state, by all means use fields of your servlet, or use classes with static fields and static getters (like the singleton pattern)
Servlets should be threadsafe. Meaning if they have any state, they should be synchronized. Try avoiding saving some state inside servlets. They should contain only business/controller logic. Any state you want to save, put them in servletcontext/request/session which are synchronized by the container.
Each servlet is executed in a new thread.. Technically, there is worker threads that waits for requests, when a http request comes to servlet container, this one instantiates a new servlet (depending to servlets defined in web.xml) and passes it to the worker thread. So logically each variable is not seen by other servlet instances. Now if you want to make your variable visible by all servlet instances you have to define it as static so it will be shared between all instances of the same class.
You should not count on two instances of a servlet even being in the same JVM. Containers can be replicated and your Servlets need to be stateless. Besides the Java EE spec does not allow you to do any threading manipulation within. The containers may allow it, but the behaviour then becomes implementation specific. By putting semaphores in there you are interfering with the pooling and can cause issues. Use Sessions if you need to differentiate between different users.

Categories

Resources