Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Exception in thread "Producer" java.lang.NullPointerException Error

843789Mar 8 2010 — edited Mar 9 2010
I am trying to implement the producer consumer problem by creating my own semaphores. When compiling and running the program I am getting the error :

Exception in thread "Producer" java.lang.NullPointerException
at Producer.run(Producer.java:23)
Exception in thread "Consumer" java.lang.NullPointerException
at Consumer.run(Consumer.java:24)

I know that this has something to do with the methods valueConsumed.P() and valueProduced.P(). Did I not implement these methods right in the Producer, Consumer, and Semaphore Classes?

Producer
public class Producer extends Thread{
	private Buffer sharedLocation;
	private Semaphore valueProduced;
	private Semaphore valueConsumed;
	
	public Producer (Buffer shared) {
		super("Producer");
		sharedLocation = shared;
	}
	
	public void run() {
		for (int count = 1; count <= 4; count++){
			try {
				Thread.sleep((int) (Math.random() * 3001));
				valueConsumed.P();
				//check to see if the value has been consumed P( valueConsumed );
				sharedLocation.set(count);
				//let consumer thread know it can consume the value
				valueProduced.V();
			}
			catch (InterruptedException exception) {
				exception.printStackTrace();
			}
		}
		System.err.println(getName() + " done producing.");
	}
}
Consumer
public class Consumer extends Thread{
	private Buffer sharedLocation;
	private Semaphore valueProduced;
	private Semaphore valueConsumed;
	
	public Consumer (Buffer shared) {
		super("Consumer");
		sharedLocation = shared;
		
	}
	public void run() {
		int sum = 0;
		for (int count=1; count<=4; count++) {
			try{
				Thread.sleep((int) (Math.random() * 3001));
				valueProduced.P();
				sum += sharedLocation.get();
				valueConsumed.V();
			}
			catch (InterruptedException exception) {
				exception.printStackTrace();
			}
		}
		System.err.println(getName() + " done consuming. and sum= " + sum);
	}
}
Semaphore
public class Semaphore{
	private int value;
	public Semaphore(int initval)
	{
		value=initval;
	}
	public void P(){
		if( value>0)
			value=value-1;
		else
			try {
				Thread.sleep((int) (Math.random() * 3001));
			}
		catch (InterruptedException exception){
			exception.printStackTrace();
		}
	}
	public void V(){
		value=value+1;
	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 6 2010
Added on Mar 8 2010
11 comments
210 views