Search code examples
javamultithreadingstaticthread-safetynon-static

Synchronization for a static and non static methods


I've a code with static and non static synchronized blocks. When I'm executing a static synchronized method I'm getting the proper output. But when i remove the static keyword from synchronized method then access it through the object of WithSync class Why i'm getting NullPointerException?

Code with Static Keyword:

    public class WithSync extends Thread {

        public static synchronized void add(int a) {
        for(int i=0;i<5;i++) {
        System.out.println(a*i);
        System.out.println(Thread.currentThread());
        }
    }
    public void run() {
        WithSync.add(5);
    }


    public static void main(String[] args) {

    WithSync t1 = new WithSync();
    WithSync t2 = new WithSync();

    t1.start();  
    t2.start();
    }
    }

**Code without Static Keyword:**

    public class WithSync extends Thread {
        WithSync ws;
        public synchronized void add(int a) {
            for(int i=0;i<5;i++) {
            System.out.println(a*i);
            System.out.println(Thread.currentThread());
            }
        }
        public void run() {
            ws.add(5);
        }


        public static void main(String[] args) {

        WithSync t1 = new WithSync();
        WithSync t2 = new WithSync();

        t1.start();  
        t2.start();
        }
    }

Exception:

Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.NullPointerException
    at com.inno.mthread.WithSync.run(WithSync.java:12)
java.lang.NullPointerException
    at com.inno.mthread.WithSync.run(WithSync.java:12)

Solution

  • First of all, you are getting error because you did not initialized your variable.

    also, you are going to do endless recursion if you initialize ws variable.

    So just stop using ws variable. I think this should work

    public class WithSync extends Thread {
        public synchronized void add(int a) {
            for(int i=0;i<5;i++) {
            System.out.println(a*i);
            System.out.println(Thread.currentThread());
            }
        }
        public void run() {
            add(5);
        }
    
    
        public static void main(String[] args) {
    
        WithSync t1 = new WithSync();
        WithSync t2 = new WithSync();
    
        t1.start();  
        t2.start();
        }
    }