Showing posts with label ThreadLocal in Java. Show all posts
Showing posts with label ThreadLocal in Java. Show all posts

Thread Methods in Java

The Thread class has methods that can be used to control the behaviour of threads. There are two constructors in thread class

    public Thread(String threadName)
    public Thread()

1. start() method

This method is used to start a new thread. When this method is called the thread enters the ready to run mode and this automatically invokes the run( ) method .

void start( )

Thread Life Cycle in Java


A thread can be in one of Four states for threads: new, runnable, blocked, dead.

Step 1: When a thread has just been created using the new operator, it is in the new state.
Step 2: Once start method is invoked (which calls the run method), the thread becomes runnable.
  • A runnable thread might not be running.
  • There can be many runnable threads. But only one of them can be running at any time point.
  • OS decides which thread to run. More on this later.
Step 3: A runnable thread enters the blocked state when
  • The thread is currently running and method Thread.sleep is called
  • suspend method of the thread is called. (deprecated)
  • The thread calls the await method.
  • The thread tries to lock an object locked by another thread.
  • The thread calls an operation that is blocked on i/o.
Step 4: A blocked reenters runnable state when
  • It has slept the specified amount of time.
  • resume method of the thread is called. (deprecated)
  • Another method calls signal or signalAll  
  • Object lock released by other thread
  • I/O completed.
Step 5: A runnable thread enters the dead state when
  • Its run method exits. Natural death.
  • stop method of the thread is called. (deprecated)
  • An exception is thrown but not caught.


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

ThreadLocal to implement a per-thread Singleton

Thread-local variables are commonly used to render stateful Singleton or shared objects thread-safe, either by encapsulating the entire unsafe object in a ThreadLocal or by encapsulating the object's thread-specific state in a ThreadLocal. For example, in an application that is tightly tied to a database, many methods may need to access the database. It could be inconvenient to include a Connection as an argument to every method in the system -- a sloppier, but significantly more convenient technique would be to access the connection with a Singleton. However, multiple threads cannot safely share a JDBC Connection. By using a ThreadLocal in our Singleton, as shown in Listing 3, we can allow any class in our program to easily acquire a reference to a per-thread Connection. In this way, we can think of a ThreadLocal as allowing us to create a per-thread-singleton.

    public class ConnectionDispenser { private static class ThreadLocalConnection extends ThreadLocal { public Object initialValue() { return DriverManager.getConnection(ConfigurationSingleton.getDbUrl()); } } private static ThreadLocalConnection conn = new ThreadLocalConnection(); public static Connection getConnection() { return (Connection) conn.get(); } }

ThreadLocal in Java

Thread-local variables are commonly used to render stateful Singleton or shared objects thread-safe, either by encapsulating the entire unsafe object in a ThreadLocal or by encapsulating the object's thread-specific state in a ThreadLocal. For example, in an application that is tightly tied to a database, many methods may need to access the database. It could be inconvenient to include a Connection as an argument to every method in the system -- a sloppier, but significantly more convenient technique would be to access the connection with a Singleton. However, multiple threads cannot safely share a JDBC Connection. By using a ThreadLocal in our Singleton, as shown in Listing 3, we can allow any class in our program to easily acquire a reference to a per-thread Connection. In this way, we can think of a ThreadLocal as allowing us to create a per-thread-singleton.


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

public class ConcurrentDateFormatAccess {

 private ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat> () {

  @Override
  public DateFormat get() {
   return super.get();
  }

  @Override
  protected DateFormat initialValue() {
   return new SimpleDateFormat("yyyy MM dd");
  }

  @Override
  public void remove() {
   super.remove();
  }

  @Override
  public void set(DateFormat value) {
   super.set(value);
  }

 };

 public Date convertStringToDate(String dateString) throws ParseException {
  return df.get().parse(dateString);
 }

}


The benefits of ThreadLocal
ThreadLocal offers a number of benefits. It is often the easiest way to render a stateful class thread-safe, or to encapsulate non-thread-safe classes so that they can safely be used in multithreaded environments. Using ThreadLocal allows us to bypass the complexity of determining when to synchronize in order to achieve thread-safety, and it improves scalability because it doesn't require any synchronization. In addition to simplicity, using ThreadLocal to store a per-thread-singleton or per-thread context information has a valuable documentation perk -- by using a ThreadLocal, it's clear that the object stored in the ThreadLocal is not shared between threads, simplifying the task of determining whether a class is thread-safe or not.

ThreadLocal in Java

ThreadLocal is a class provides way to hold thread local variables and provide access to get and set values. in other words, it allows you to have copy of variables per thread and thesevariables will be garbage collected when the associated thread dies. ThreadLocal instances are advised to be private static fields in classes.For example, check the Audit class bellow
1
2
3
4
5
6
7
8
9
10
11
class Audit {
 private static ThreadLocal auditDetails = new ThreadLocal();
 
 public static String get() {
  return (String) auditDetails.get();
 }
 
 public static void set(String details) {
  auditDetails.set(details);
 }
}

Here, auditDetails is a thread local variable. The set(String) method of Audit class sets a value in thread local variable auditDetails. As auditDetails is a static, it will be shared with multiple threads but the value which is set will belong to only the current thread.The JVM finds the current thread and associate the value. And when get(String) method of Audit is called, the auditDetails returns the value associated with current thread. The following example will help you to understand it more.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package basics;
 
public class ThreadLocalExamples {
 
 public void methodA() {
   
  //Generates a random value
  int value = (int)(Math.random()*100);
   
  //Prints the current thread and the generated random value
  System.out.println("Setting " +value+ " to " +Thread.currentThread().getName());
   
  //Set the random value as audit details
  Audit.set(String.valueOf(value));
   
  //Keeping the threads on sleep mode for some time
  try {
   Thread.sleep(value);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  methodB();
 }
 
 public void methodB() {
   
  //Just prints the audit details value set for the current thread
  System.out.println(Thread.currentThread().getName()+":"+Audit.get());
 }
 
 public static void main(String[] args) {
 
  final ThreadLocalExamples examples = new ThreadLocalExamples();
 
  //Creates thread one and call methodA() on examples
  Thread threadOne = new Thread() {
   public void run() {
    examples.methodA();
   }
  };
   
  //Creates thread two and call methodA() on the same instance examples
  threadOne.setName("ThreadOne");
  Thread threadTwo = new Thread() {
   public void run() {
    examples.methodA();
   }
  };
  threadTwo.setName("ThreadTwo");
 
  //Starting the threads
  threadOne.start();
  threadTwo.start();
 }
}
if you look at the code, there are two methods methodA() and methodB().The methodA() generates a random number and set it as audit details and calls the methodB().The static method set(string) in Audit class is called to set audit details to the thread local .The methodB() gets the audit details and prints it. The static method get() in Audit class is called to get audit details from thread local. The main method creates creates one instance of ThreadLocalExamples and two instances of threads. Both thread instances call the methodA() of same instance of ThreadLocalExamples in their run() method.
Note: The same instance of ThreadLocalExamples is accessed by two threads at the same time.
If you run the program, you will get something like the following output

Setting 13 to ThreadOne
Setting 67 to ThreadTwo
ThreadOne:13
ThreadTwo:67


if you analyze the output results, Thread one sets ‘13 ‘ to thread local, then Thread two sets ‘67 ‘ to thread local.Even though both threads access the same thread local instance to set the value. the values are set to the current thread’s local values. That’s why when it prints the value, the value associated to the current thread is retrieved and printed.

So one again i say it, ThreadLocal is a class provides way to hold thread local variables and provide access to get and set values. in other words, it allows you to have copy of variablesper thread and these variables will be garbage collected what the thread dies.


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email