0

Consider the following code:

class Chicks {
       synchronized void yack(long id) {
                       for(int x = 1; x < 3; x++) {
                                   System.out.print(id + " ");
                                   Thread.yield();
                        }
       }
}
public class ChicksYack implements Runnable {
      Chicks c;                                //.....(1)
      public static void main(String[] args) {
                       new ChicksYack().go();
      }
      void go() {
                      c = new Chicks();        //........(2)
                      new Thread(new ChicksYack()).start();
                      new Thread(new ChicksYack()).start();
      }
      public void run() {
                      c.yack(Thread.currentThread().getId());
      }
}

When i run this code, I am getting a Null Pointer Exception that I have not initialized variable c. But didn't i initialized it at line ....(2)? I am having trouble getting this concept. Does threading has a part to play in this exception?

1
  • Which line gives the NPE? Commented Jun 28, 2013 at 23:59

2 Answers 2

4

Look at this line:

new Thread(new ChicksYack()).start();
           ^^^^^^^^^^^^^^^^

The attribute c of the newly created ChicksYack object is never initialized. In the go() method you only initialize c for the current (this) object.

That's why you get an NPE in the run() method. A good solution would be to initialize that variable in a default constructor for ChicksYack.

Sign up to request clarification or add additional context in comments.

1 Comment

Or even better, just initialise it at the point of declaration (since it doesn't require any external state).
0

In the go() method, you're instantiating two new ChickYack objects, which have a null c. You should put the c = new Chicks() in your ChicksYack constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.