Wednesday, January 16, 2013

What is Threadlocal in Java? When to use Threadloacal?


Thread-Local means local to thread.In Context of java ,Thread-local means "every thread that will access thread-local variable will have its own  instantiated copy of variable ".

See the below example:
If you look the output of above program than you will find that when different thread calls getDateFormatter() method of SimpleDateFormatPerThread class than its call its initialValue() method which creates exclusive instance of SimpleDateFormat for that Thread. Since SimpleDateFormat is not shared between thread and essentially local to the thread which creates its our threadSafFormat() method is completely thread-safe.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


public class ThreadLocalTest
{

    public static void main(String[] args)
    {
        Thread t1 = new Thread(new ThreadTask());
        Thread t2 = new Thread(new ThreadTask());
       
        t1.start();
        t2.start();
       
       
    }
}


class SimpleDateFormatPerThread
{
     private static final ThreadLocal<SimpleDateFormat> dateFormatHolder = new ThreadLocal<SimpleDateFormat>() {

            /*
             * initialValue() is called
             */
            @Override
            protected SimpleDateFormat initialValue() {
                System.out.println("Creating SimpleDateFormat for Thread : " + Thread.currentThread().getName());
                return new SimpleDateFormat("dd/MM/yyyy");
            }
        };

        /*
         * Every time there is a call for DateFormat, ThreadLocal will return calling
         * Thread's copy of SimpleDateFormat
         */
        public static DateFormat getDateFormatter() {
            return dateFormatHolder.get();
        }

       
        /*
         * Thread safe format method because every thread will use its own DateFormat
         */
        public static String threadSafeFormat(Date date){
            DateFormat formatter = SimpleDateFormatPerThread.getDateFormatter();
            return formatter.format(date);
        }



}


class ThreadTask implements Runnable
{

    @Override
    public void run()
    {
        for (int i = 0; i < 2; i++) {
            System.out.println("Thread name"+Thread.currentThread().getName()+"  "+SimpleDateFormatPerThread.threadSafeFormat(new Date()).toString());
        }
    }
   
}


 Output:
/*
Creating SimpleDateFormat for Thread : Thread-1
Creating SimpleDateFormat for Thread : Thread-0
Thread nameThread-0  16/01/2013
Thread nameThread-0  16/01/2013
Thread nameThread-1  16/01/2013
Thread nameThread-1  16/01/2013

/* 




To get more clarity about thread safety issue with SimpleDateFormat class ,just go through below link:

http://www.codefutures.com/weblog/andygrove/2007/10/simpledateformat-and-thread-safety.html




















Sunday, January 13, 2013

Rakesh Blogspot: What is Singleton? Where it is required?

Rakesh Blogspot: What is Singleton? Where it is required?

What is Singleton? Where it is required.

Q : What is a singleton pattern? How do you code it in Java? DP MI CO
Ans: A singleton is a class that can be instantiated only one time in a JVM per class loader. Repeated calls always
return the same instance. Ensures that a class has only one instance, and provide a global point of access. It
can be an issue if singleton class gets loaded by multiple class loaders.
public class OnlyOne {
private static OnlyOne one = new OnlyOne();
private OnlyOne(){… } //private constructor. This class cannot be instantiated from outside.
public static OnlyOne getInstance() {
return one;
}
}
To use it:
//No matter how many times you call, you get the same instance of the object.
OnlyOne myOne = OnlyOne.getInstance();

Note: The constructor must be explicitly declared and should have the private access modifier, so that it cannot be
instantiated from out side the class. The only way to instantiate an instance of class OnlyOne is through the
getInstance() method with a public access modifier.
When to use: Use it when only a single instance of an object is required in memory for a single point of access.
For example the following situations require a single point of access, which gets invoked from various parts of
the code.
􀂃 Accessing application specific properties through a singleton object, which reads them for the first time from
a properties file and subsequent accesses are returned from in-memory objects. Also there could be
another piece of code, which periodically synchronizes the in-memory properties when the values get
modified in the underlying properties file. This piece of code accesses the in-memory objects through the
singleton object (i.e. global point of access).
􀂃 Accessing in-memory object cache or object pool, or non-memory based resource pools like sockets,
connections etc through a singleton object (i.e. global point of access).
What is the difference between a singleton class and a static class? Static class is one approach to make a class singleton
by declaring the class as “final” so that it cannot be extended and declaring all the methods as static so that you can’t create any
instance of the class and can call the static methods directly.