Question

I defined a public volatile LinkedList to be shared with some threads, and I synchronize it within main() which is static... so I get a compile error : " cannot make a reference to a non static field"

If I modify the definition to be public volatile static LinkedList, then I get an exception :

 Exception in thread "filteringThread" java.lang.NullPointerException
at com.swimtechtest.swimmerbench.FilteringThread.run(FilteringThread.java:39)

here is part of my code

public class SwimmerBench{
    ...
    public volatile LinkedList<InterpolatedEvent> samplings = new LinkedList<InterpolatedEvent>();
    ...
    public static void main(String args[]) throws IOException {
       ...
       InterpolatedEvent event = createInterpolatedEvent(fields);
   synchronized(samplings){
        samplings.add(event);
    samplings.notifyAll();
   }
       ...
    }
}

  ======

public class FilteringThread extends Thread {

    LinkedList<InterpolatedEvent> samplings;
       public void run() {

   System.out.println("Running " +  threadName );

  while(running ) {
      try {
        synchronized(samplings) { // <=  exception error line 39
            InterpolatedEvent event = samplings.getLast();
            samplings.notifyAll();
       }
  }
}
Was it helpful?

Solution

I defined a public volatile LinkedList to be shared with some threads, and I synchronize it within main() which is static... so I get a compile error : " cannot make a reference to a non static field"

It's not related to volatile or synchronization, it's because you are accessing instance variable samplings in static main() method.

If I modify the definition to be public volatile static LinkedList, then I get an exception :

 Exception in thread "filteringThread" java.lang.NullPointerException
at com.swimtechtest.swimmerbench.FilteringThread.run(FilteringThread.java:39)

This is because, your instance variable samplings in FilteringThread is never assigned to an object of type List. It's assigned by default null

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top