Sunday, October 31, 2010

Java Threading

public static void myMethod(){
    synchronized(this){
        //do stuff
    }
}

This will not get a class level lock, many threads can enter this static method of class and with individual object lock can execute code in it.

public static synchronized void myMethod() {
    //do stuff
}
-----is equivalent to-----
public void myMethod(){
    synchronized(MyClass.class){
         //do stuff
    }
}

In both the case, threads will obtain a class level lock butt there will just be a difference of timing for how long lock is being obtained.

1. Threads that synchronize on the same object will block each other. Threads that synchronize on different objects will not.
2. A static synchronized method and a non-static synchronized method will not block each other, ever. The static method locks on a class instance while non-static method locks on this instance these actions do not interfere with each other at all.
3. Threads calling static synchronized methods in the same class will always block each other - they all lock the same class instance.
4. Threads calling non-static synchronized methods in the same class will only block each other if they are invoked using same instance.
5. A thread can acquire more that one lock. A thread can enter a synchronized method, acquiring a lock and then immediately invoke a synchronized method on a different object, acquiring that locak as well. A thread acquires a lock and then attempts to call a synchronized method on the same object, no problem because thread already have lock of this object.
6. If a class has both synchronized and non-synchronized methods, multiple threads can still access the class's non-synchronized methods.

Thread Join-
If you have a thread B that can't do its work until another thread A has completed its work, then you want B to join thread A.
This means that thread B will not become runnable until thread A has finished.
Thread t = new Thread();
t.start();
t.join();
This code take currently running thread and joins it to the end of thread t. Current thread become runnable after thread t is no longer alive.

No comments:

Post a Comment