0

I want to update a class attribute (the class is extending Thread) in the run() method, I do it like so:

public class ClassProcessing extends Thread {

    volatile public List<String> processedList ;
    
    ...
    
    public void run() {
    
      ....
      String processedElement = ....
    
      this.processedList.add(computedElement);
    }

Doing like so returns java.lang.NullPointerException: Cannot invoke "java.util.List.add(Object)" because "this.processedList" is null

How to solve this? Thanks.

Sam
  • 308
  • 2
  • 7

1 Answers1

1

First, you have not initialized processedList, or at least it's not shown in your code snippet.

Second, you use volatile on the processedList field, but this does not help to make your code thread-safe. volatile only affects the reference in the field itself, not the list object. Instead you should use a thread-safe class, like CopyOnWriteArrayList or ConcurrentLinkedDeque.

rolve
  • 10,083
  • 4
  • 55
  • 75
  • could explain what do you mean by thread-safe? – Sam Feb 02 '23 at 11:34
  • 1
    If you don't know that thread-safe means, you should read up on that before using threads. Unfortunately, this is probably not something you can do in a few minutes. There are whole classes at universities dealing with concurrency and thread-safety. One book I recommend is: https://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601 – rolve Feb 02 '23 at 11:40
  • I'd recommend [The Java Tutorials](https://docs.oracle.com/javase/tutorial/) for Oracle as a good starting point. It covers the basics of the language, the collections framework, and up to advanced topics such as threads and concurrency. I agree with @rolve that writing code that uses threads is better left until after you have mastered the fundamentals. – Tim Moore Feb 02 '23 at 11:56