-1

I wrote this program to sync multiple threads, the functionality of this prog is each runner thread gets some random value and we need to sort them in order but the prog some times get null pointer exception some times not. this is relayrace.java

package com.mani.threadstrail;
import java.util.Random;

import java.util.LinkedList;
import java.util.List;

public class RelayRace extends Thread{

public static void main(String[] args) {
    // TODO Auto-generated method stub

   for(int i=0;i<10;i++)
   {
       RelayRace r= new RelayRace();
       r.setName("runner-"+ i);
       r.start();
   }
  try {
    Thread.sleep(1000);
    Runner.sortings();
    Runner.printlist();

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


}

public void run() {
    Random rand = new Random();

    int  n = rand.nextInt(50) + 1;
    System.out.println(Thread.currentThread().getName()+"  "+ n);
    Runner r1 = new Runner(n,Thread.currentThread().getName());
    r1.add();
}

}

this is runner.java

package com.mani.threadstrail;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;


public class Runner implements Comparable<Runner> {

  static List<Runner> a = new LinkedList<Runner>();

  public int speed;
  public String name;
  Runner(int speed,String name){
      this.name=name;
      this.speed= speed;
  }
  public synchronized void add() {

      a.add(this);

  }
  static synchronized void printlist() {
      for(Runner st:a){  
          System.out.println(st.speed+" "+st.name);  
      }
  }
 static void sortings() {
     Collections.sort(a);
 }

@Override
public int compareTo(Runner o) {
    return -(this.speed-o.speed);
}

}

Manikanta P
  • 2,777
  • 2
  • 19
  • 22

1 Answers1

2

You get an NPE because there are null elements in the list when you try to sort it.

How do these get in there? You don't add them...

Well, your synchronization on the list a is not correctly done.

  • In Runner the method add() synchronizes on this.
  • printlist() however synchronizes on Runner.class, as it's a static method.
  • sortings() doesn't synchronize at all, even though it does modify the list.

Using proper synchronization (by synchronizing all three acceses on Runner.class for instance) you'll get rid of the NullPointerExceptions

bowmore
  • 10,842
  • 1
  • 35
  • 43