Tuesday, 3 July 2012

If a synchronized method calls another non-synchronized method, is there a lock on the non-synchronized method?

If you are in a synchronized method then calls to other methods that are also synchronized are locked however calls to non-synchronized are not locked -- any method can call them at the same time.
public synchronized void synchronizedMethod() {
    ...
    nonSynchronizedMethod();
    ...
}

/* any method can call this method even if the synchronizedMethod() method has been called and the lock has been acquired*/
public void nonSynchronizedMethod() {
   ...
}
Everything in the synchronized method have a lock on it (including calls to other synchronized methods).
Other calls to synchronized methods are locked. But non-synchronized methods are not locked.
Also, remember that if the method is static then the lock is on the Class object in the ClassLoader.
If the method is an instance method then the lock is on the instance Object.
// this locks on the Class object in the ClassLoader
public synchronized void nonStaticSynchronizedMethod(){
       staticSynchronizedMethod();
}
public static synchronized void staticSynchronizedMethod(){
 ....
}
/* this locks on the instance object that contains the method and any method can call staticNonSynchronizedMethod() method at the same time */
public synchronized void nonStaticSynchronizedMethod(){
 staticNonSynchronizedMethod();
}
public static void staticNonSynchronizedMethod(){
 ....
}
/*this locks on the instance object that contains the method and any method can call nonStaticNonSynchronizedMethod() method at the same time */
public synchronized void nonStaticSynchronizedMethod(){
 nonStaticNonSynchronizedMethod();
}
public void nonStaticNonSynchronizedMethod(){
 ....
}
//any method can call staticNonSynchronizedMethod at the same time
public static synchronized void staticSynchronizedMethod(){
 staticNonSynchronizedMethod();
}
public static void staticNonSynchronizedMethod(){
 ....
}
//any method can call staticNonSynchronizedMethod at the same time
public static synchronized void staticSynchronizedMethod(){
 nonStaticNonSynchronizedMethod();
}
public void nonStaticNonSynchronizedMethod(){
 ....
}
Download examples here

Monday, 2 July 2012

What is the difference between HttpServletResponse methods setHeader(), addHeader() and setIntHeader()?

void setHeader(String name, String value)
If a header with this name already in response, then that header value is replaced with this value. Otherwise adds a new header and value to the response.

void addHeader(String name, String value)
If a header with this name already in response, then adds an additional value to the existing header. Otherwise adds a new header and value to the response.

void setIntHeader(String name, int value)
If a integer type header with this name already in response, then replaces that header value with this new integer value. Otherwise adds a new header and value in response.