0
protected static Object lock;
public void awake(){
    synchronized (lock){
        if(Thread.currentThread().isAlive()){
        Thread.currentThread().notify();
        }
    }
}

I am using this code in a synchronized block so that my main method has a monitor of the thread and doesn't receive a IllegalMonitorStateException.

I don't understand why this is giving me a nullpointer exception. The thread has to be alive to execute the thread.notify command, and the lock is a static object. Nothing can be null. Any ideas?

Jacob
  • 57
  • 8
  • You need to assign a non-null value to `lock` first. – Andy Turner Oct 12 '16 at 16:10
  • 1
    lock is null in your snippet... a debugger or a print out wouldve verified this as well. – Jason C Oct 12 '16 at 16:11
  • The linked duplicate doesn't actually specify that you need to have a non-null value used with `synchronized`, but that's quickly fixed... – Makoto Oct 12 '16 at 16:12
  • 1
    The take home point from the link is "something is null". The next step presuming its not apparent by looking at the code is to find out what. So thats an applicable lesson from the dupe at least. – Jason C Oct 12 '16 at 16:13
  • How is lock null? How would i make it something that isn't null? This is how my teacher initialized locks in the tutorial. This is also what I see when I look it up. Sorry for my ignorance, I'm having a lot of trouble with this – Jacob Oct 12 '16 at 16:13
  • Also the line number in the exception should clearly point to `synchronized (lock)`, where there is exactly one option for the thing that is null. – Jason C Oct 12 '16 at 16:14
  • @Jacob: You haven't explicitly stated `lock = new Object()` anywhere after declaring `lock`, hence it defaults to `null` when the class is instantiated. – Makoto Oct 12 '16 at 16:15
  • What do you mean how is lock null? All fields, static or not, are initialized to null or 0. You have to assign something to it. A `new Object()` is a good start. – Jason C Oct 12 '16 at 16:15
  • How is lock null? How is it **not** null? – Hovercraft Full Of Eels Oct 12 '16 at 16:15
  • It should also be mentioned that you are only allowed to call `notify()` on an object when you are synchronized on that object. Meaning, you need to call `lock.notify()`, not the Thread’s notify(). – VGR Oct 12 '16 at 16:53

1 Answers1

0

Just because it's static doesn't mean it's never going to be null. You need protected static Object lock = new Object();

Alex A
  • 368
  • 2
  • 7