Thursday, September 1, 2011

Static and Non Static Synchronized Methods

Hi Friends,

This is my first post. I hope you will like this one.

Have you ever thought about the behavior of a static synchronized method call and a non-static synchronized method call in Java? Before that, first of all we should have a look on how the static and non static calls work -


Static Method Call - When we make a call to a static method (either directly from class or any object of that class), the Class object of that Class involves in that call. Every Class has only one Class object.

Non-static Call When we call a non-static method (always from an object of that class), it works for that object only (which is of that class only). A class can have as many objects (if not restricted though some design patterns or lack of memory).

Now, lets come to Static and Non-static Synchronized method calls -

Static Synchronized Method Call - Whenever a thread accesses any synchronized static method, it acquires the lock on Class object of that class and hence no other static method can be accessed of that class.

Non-static Synchronized Method Call - As the non-static methods can be accessed through only objects of that class. So whenever, a thread enters any non-static synchronized method, it acquires the lock on the object through which the call has been made. Hence the other threads can still access the same or other non-static methods using other unlocked objects (free resources) of that class.

Thanks

6 comments:

  1. Static Synchronized Method Call -...it acquires the lock on Class object of that class and hence no other static method can be accessed of that class.

    (Do you think there are something wrong? )
    Prefer following code:

    public class Main{

    public static void main(String[] args) {
    B m1 = new B("m1");
    m1.start();

    for (int i = 0; i < 10; i++){
    B.bMethod();
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    }

    }

    class B extends Thread{

    public B (String name) {
    super(name);
    }

    public void run() {
    aMethod();
    }

    public static synchronized void aMethod() {
    for(int i=0;i<10; i++){
    System.out.println(Thread.currentThread().getName()+" aMethod.. ");
    try {
    sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }

    public static void bMethod() {
    System.out.println(Thread.currentThread().getName() + " bMethod.. ");
    }

    }

    ////-------- Print Result:
    main bMethod..
    m1 aMethod..
    main bMethod..
    m1 aMethod..
    main bMethod..
    m1 aMethod..
    m1 aMethod..
    main bMethod..
    main bMethod..
    m1 aMethod..

    ReplyDelete