0

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) 
1
  • In the code you posted, you never initialize your ws variable. So it's null, which leads to a NPE... Commented Dec 18, 2019 at 6:49

1 Answer 1

1

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(); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

working but. I'm getting doubt that When i access static method i don't need to create object for the class i can access with class name that time it wasn't showing any error why now after creating object for that class?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.