I have been working on brushing up on my java for employment/education purposes, so I've been going back and redoing all my undergrad projects, trying to make them better/more functional/etc.
Well I had a working product, but then I did something and I'm suddenly getting a null pointer on one of my threads. Is there a way I am supposed to initialize the thread? Lines 76 & 77 is where it is first called. It's pretty simple, so I don't know what the problem is.
Because of this, there's no message stream printing. If you could provide some assistance, or somewhere where I could learn more about properly initializing threads, I would greatly appreciate it.
The problem would be easier to diagnose if you show us the error and stack trace. It does not look like lines 76 & 77 can cause a NullPointerException.
If I were to guess, the problem is probably in the run() method. It uses the reader which does not get initialized until after the user logs in and connects. So the thread should probably not be started until the user connects.
also note that Swing components are not thread safe. Doing read.append() in your IncomingMessages thread is not safe. You should push that into the EDT using SwingUtilities.
posted 7 years ago
Thanks so much for the quick reply. You are GOOD, I moved the thread into the LoginAction method, and it worked perfectly. Just for my personal development, how did you catch that? I hate bothering people for help, so I've been staring at this code on and off all day, and that never occurred to me, and never would have. What were you looking for?
What I started with was the two lines you gave me, 76 and 77. Since those two lines only used local Objects which were initialized in-place, they could not be null. So assuming the Thread did have something to do with the problem, I looked at the code the Thread executes. It uses a reference (reader) that is not initialized locally which is a prime suspect for a NullPointerException. So I looked through the code for when that variable would be initialized. Because the variable was only initialized only after user interaction it was clear the reader was the problem.
But stack traces make the problem so much easier to find. You would see something like:
This would tell you what line of code (Client.java line 193, inside the IncomingMessages run() method). That would point you directly to the while ((message = reader.readLine()) != null) line. From there you see that there is only one Object being deferenced, reader and so that would be the only possible cause of the NullPointerException.
posted 7 years ago
Awesome. I should have thought of that. Thanks again for your help.