0

This is the code I have. I have getting Null Pointer Exception in the last line of the constructor (workerQueue[i] = new LinkedBlockingQueue(100);):

public class QueueThreadPool {

  private BlockingQueue<String>[] workerQueue;
  private Thread[] workerThreads;
  private int numQueues;
  private int numThreads;

public QueueThreadPool(int numThreads, int numQueues) {
    this.numQueues = numQueues;
    this.numThreads = numThreads;

    for(int i=1; i<=numQueues; i++){
        workerQueue[i] = new LinkedBlockingQueue<String>(100);
    }
}
public static void main(String args[]){
    System.out.println("Start...");
    new QueueThreadPool(50, 11);
    System.out.println("End...");
}

Please help! Thanks!!

3 Answers 3

2

Array workerQueue is not instantiated which you need to do.

private BlockingQueue<String>[] workerQueue;

workerQueue is a reference of BlockingQueue<String>[] type, not a Object.

But also you cannot create a generic array of BlockingQueue<String>. Instead of that create a List of BlockingQueue<String>. Ex -

private List<BlockingQueue<String>> workerQueue= new ArrayList<>();

you can also create the list Object at constructor.

private List<BlockingQueue<String>> workerQueue= new ArrayList<>();
public QueueThreadPool(int numThreads, int numQueues) {
    this.workerQueue = new ArrayList<>(numQueues);  // <-- initialize the field.
    this.numQueues = numQueues;
    this.numThreads = numThreads;
    ...
Sign up to request clarification or add additional context in comments.

Comments

0

You haven't initialized workerThreads. You have to do something like workerQueue= new BlockingQueue<String>[numQueues];

1 Comment

Thanks for the reply. As mentioned int he ab ove answer, this declaration creates a generic array, which again gives error.
0

Two problems in the code: the field need to be initialized, the loop should go from 0 to the array-size's - 1. Here is how the fixed code should look like:

public class QueueThreadPool {

  private BlockingQueue<String>[] workerQueue;
  private Thread[] workerThreads;
  private int numQueues;
  private int numThreads;

public QueueThreadPool(int numThreads, int numQueues) {
    this.workerQueue = new BlockingQueue<String>[numQueues]  // <-- You need to initialize the field.
    this.numQueues = numQueues;
    this.numThreads = numThreads;

    for(int i=0; i < numQueues; i++){  // <-- Indexing into arrays goes from 0 to size-1     (inclusive).
        workerQueue[i] = new LinkedBlockingQueue<String>(100);
    }
}

1 Comment

Thanks for the reply. As mentioned in the above answer, this declaration creates a generic array, which again gives error.

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.