public static void getResult(HttpSession session) {
synchronized(session) {
....
}
}
Here synchronized block is on session, but the method is a static one. Does this result in a class level locking?
public static void getResult(HttpSession session) {
synchronized(session) {
....
}
}
Here synchronized block is on session, but the method is a static one. Does this result in a class level locking?
A thread will take a lock on the session
object you have used in synchronized(session)
. In your case it does not matter if the method is static or not, in both case lock, will be on the session object.
To answer your question: Is this a class level lock? The answer is hmm, no :)
Different threads here can sync on different objects as the lock is brought as parameter to the method.
A couple of examples:
public class DemoClass
{
//Method is static
public synchronized static void demoMethod(){
}
}
or
public class DemoClass
{
public void demoMethod()
{
//Acquire lock on .class reference
synchronized (DemoClass.class)
{
//other thread safe code
}
}
}
or
public class DemoClass
{
private final static Object lock = new Object();
public void demoMethod()
{
//Lock object is static
synchronized (lock)
{
//other thread safe code
}
}
}
Syncronisation brings overhead to your program. In a web application it is one of the responsabilities that the Application Container takes for you. Eventhough you could span own threads in a web app, it is discouraged.