I was trying a Producer/Consumer Problem, but I don’t know why I am getting java.lang.NullPointerException inside the Consumer.
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class Producer extends CommonClass implements Runnable {
private int producerNum;
Producer(PriorityBlockingQueue<Character> queue) {
queue = queue;
}
public void run() {
char ch;
for (ch = 'a'; ch <= 'z'; ch++) {
queue.add(ch);
System.out.println("Producer" + producerNum + "produced :" + ch);
try {
Thread.sleep((int) (Math.random() * 300));
} catch (InterruptedException e) {
System.out.println("Error");
}
}
}
}
This is my Consumer class
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class Consumer extends CommonClass implements Runnable {
private int consumerNum;
Consumer(PriorityBlockingQueue<Character> queue )
{
queue = queue;
}
public void run() {
char c;
for (int i = 0; i < 27; i++) {
c = queue.poll();
System.out.println("Consumer" + consumerNum + "consumed:" + c);
try {
Thread.sleep((int) (Math.random() * 300));
} catch (InterruptedException e) {
System.out.println("Error");
}
}
}
}
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class CommonClass {
PriorityBlockingQueue<Character> queue = new PriorityBlockingQueue<Character>();
}
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class SyncTest {
public static void main(String[] args) {
PriorityBlockingQueue<Character> queue = new PriorityBlockingQueue<Character>();
Producer p1 = new Producer(queue);
Thread t1 = new Thread(p1);
t1.start();
Consumer c1 = new Consumer(queue);
Thread ct1 = new Thread(c1);
ct1.start();
}
}
This is the exception I get:
Exception in thread "Thread-1" java.lang.NullPointerException
at com.Consumer.run(Consumer.java:18)
at java.lang.Thread.run(Unknown Source)
This is the immediate problem:
That’s a no-op statement, assigning the parameter’s value back to itself. You want:
Once you’ve fixed that, you’ll then have a potential problem due to calling
poll()(decalred inQueue), which will returnnullif the queue is empty. That null reference will then be unboxed to assign the value to thecvariable (of typechar).Use
take()(declared inBlockingQueue) instead, which will block. You may want to specify a timeout, too.