0

I am trying to spread a time-taking loop over many threads, and I get a NullPointerException for some reason. I checked if the thread_array was empty, but it wasn't. Any suggestions at what I am doing wrong? Here is my code:

Inner Thread Class

class RowAndThetaThread implements Runnable{
    private int x_0;
    private int y_0;

    public void run() {
        // do something
        thread_semaphore.release();
    }

    public void input_elements(int x, int y) {
        x_0 = x;
        y_0 = y;
        try {
            thread_semaphore.acquire();
        } catch (Exception e) {}
        this.run();
    }

    public void lol() {
        System.out.println("LOLOLOLOL");
    }
}

Thread Calling

    RowAndThetaThread[] thread_arr = new RowAndThetaThread[LENGTH];

    thread_semaphore = new Semaphore(thread_arr.length, false);
    for (int i=0; i<border_que.arr.length; i++) {
        thread_arr[i].lol(); // NullPointerException happens here
    }
tung
  • 719
  • 2
  • 14
  • 30
SalmonKiller
  • 2,183
  • 4
  • 27
  • 56

2 Answers2

1

You create thread array but do not initialize the array element, so initialize the thread array element. See the following code snippet

RowAndThetaThread[] thread_arr = new RowAndThetaThread[LENGTH];

// Initialization of thread_arr element
for (int i=0; i<border_que.arr.length; i++) {
    thread_arr[i] = new RowAndThetaThread();
}

thread_semaphore = new Semaphore(thread_arr.length, false);
for (int i=0; i<border_que.arr.length; i++) {
    thread_arr[i].lol(); // NullPointerException happens here
}
BeingMIAkashs
  • 1,375
  • 11
  • 18
1

The problem is that you are creating an array for RowAndThetaThread objects, but you aren't populating it with those objects. In Java, arrays of objects are null by default.

  // You declare the array here
RowAndThetaThread[] thread_arr = new RowAndThetaThread[LENGTH];
...

thread_arr[i].lol(); // NullPointerException happens here

Because the array is full of nulls, you get a NullPointerException there. To fix this, you'll have to populate the array. Something like this:

RowAndThetaThread[] thread_arr = new RowAndThetaThread[LENGTH];
for(int i = 0; i < thread_arr.length; i++) {
    thread_arr[i] = new RowAndThetaThread();
}
thread_semaphore = new Semaphore(thread_arr.length, false);
for (int i=0; i<border_que.arr.length; i++) {
   thread_arr[i].lol(); // NullPointerException happens here
}
Todd
  • 30,472
  • 11
  • 81
  • 89