0

I'm currently working on a pipe system in Java where many processors can write in it and read from it. The code compiles without any errors but when I try to run it, it throws me the following exception: Exception in thread "main" java.lang.NullPointerException at Processor.main(Processor.java:42)

And here is my code so far:

class Pipe {
    private float[] buffer;
    private boolean buffer_blocked;

public Pipe() {
    this.buffer = new float[10];
    this.buffer_blocked = false;
}

public synchronized void send(int chnl, float value) {
    while (buffer_blocked) {
        try {
            wait();
        } catch(InterruptedException e) {}
    }
    buffer_blocked = true;
    buffer[chnl] = value;
    buffer_blocked = false;
    notifyAll();
}

public synchronized float receive(int chnl) {
    while (buffer_blocked) {
        try {
            wait();
        } catch(InterruptedException e) {}
    }
    return buffer[chnl];
}
}

public class Processor {
private static Pipe pipe;

public Processor() {
    // empty constructor
}

public static void main(String[] args) {
    Processor P1 = new Processor();
    Processor P2 = new Processor();
    P1.pipe.send(0, 6.1f);         // write
    float number = P2.pipe.receive(0); // read;
    System.out.println(number); // should print 6.1
}
}

I read something about that the array must not contain null pointers when it comes to setting values but I didn't use null pointers. I appreciate any kind of help, thanks in advance!

M. Gruber
  • 33
  • 1
  • 4
  • Look at your Processor class and look to see how `pipe` is instantiated before it is used. It simply doesn't exist, until you instantiate it which you should probably do in your constructor. And does it really need to be statically defined? This is why you get a `NullPointerException`. – ManoDestra May 26 '16 at 19:33
  • 1
    It worked, thanks! I thought it needs to be statically defined because each new defined processor uses the same shared pipe. – M. Gruber May 26 '16 at 19:54
  • You could create the pipe separately as a singleton and pass it to each Processor via its constructor, but yeah, I see where you're coming from :) – ManoDestra May 26 '16 at 21:41

0 Answers0