dimanche 10 septembre 2017

Why do SimpleDateFormat Constructor return the same Object for different Threads?

I was fiddling with Threads and was trying out the following code

 import java.text.SimpleDateFormat;

 public class SimpleDateFormatTest {    

    public static void main(String[] args) {


      Thread A=new Thread(()->{
          SimpleDateFormat a=new SimpleDateFormat("yyyy-MM-dd");
          System.out.println(Thread.currentThread().getName()+" "+a);
          });
      Thread B=new Thread(()->{
          SimpleDateFormat b=new SimpleDateFormat("yyyy-MM-dd");
          System.out.println(Thread.currentThread().getName()+" "+b);
          });   


      A.start();
      B.start();

    }

}

The output i got was as follows :

  • Thread-0 java.text.SimpleDateFormat@f67a0200
  • Thread-1 java.text.SimpleDateFormat@f67a0200

Can anyone tell me why same object is passed around for two Threads , when i have assigned individual new object to two Separate Thread local variables (a & b),for sake of thread-safety ?

Thanks in Advance!!

Aucun commentaire:

Enregistrer un commentaire