MultiThreaded Programming is always special in java. It has lot to do. In such cases we will face problems like sharing of variables (which has static specifier in my case). Synchronization is not exactly suitable then we can use thread local.
Java
ThreadLocal
is used to create thread-local variables. We know that all threads of an Object share it’s variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables.
Every thread has it’s own
ThreadLocal class is extend in Java 8 with a new method
ThreadLocal
variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.ThreadLocal class is extend in Java 8 with a new method
withInitial()
that takes Supplier functional interface as argument. So we can use lambda expressions to easily create the ThreadLocal instance.
Here is a small example showing use of ThreadLocal and proving that every thread has it’s own copy of ThreadLocal variable.
public class XmlParserProcessor {
//Variable for each thread stack when more number of threads running simultaneously .
public static final ThreadLocal<Integer> count = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue()
{
return 0;
}
};
public static void set(int skippedCount) {
skippedListCount.set(skippedCount);
}
public static void unset() {
skippedListCount.remove();
}
public static int get() {
return skippedListCount.get();
}
}
No comments:
Post a Comment