<div class="entry-content" itemprop="text"><!-- Quick Adsense WordPress Plugin: http://quickadsense.com/ --> <div style="float: none; margin:10px 0 10px 0; text-align:center;"> <div data-type="ad" data-publisher="journaldev.com" data-zone="jd_after_entry_728x90" data-format="728x90"> </div> </div> <p>Java ThreadLocal is used to create thread local variables. We know that all threads of an Object share it’s variables, so the variable is not thread safe. We can use synchronization for thread safety but if we want to avoid synchronization, we can use <code>ThreadLocal</code> variables.</p> <h2>Java ThreadLocal</h2> <p><a href="//cdn.journaldev.com/wp-content/uploads/2012/12/threadlocal-java.jpg"><img src="//cdn.journaldev.com/wp-content/uploads/2012/12/threadlocal-java.jpg" alt="ThreadLocal, Java ThreadLocal" width="560" height="315" class="aligncenter size-full wp-image-12304" srcset="//cdn.journaldev.com/wp-content/uploads/2012/12/threadlocal-java.jpg 560w, //cdn.journaldev.com/wp-content/uploads/2012/12/threadlocal-java-450x253.jpg 450w, //cdn.journaldev.com/wp-content/uploads/2012/12/threadlocal-java-20x11.jpg 20w" sizes="(max-width: 560px) 100vw, 560px"></a></p> <p>Every thread has it’s own <code>ThreadLocal</code> variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread. </p> <p>ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.</p> <h3>Java ThreadLocal Example</h3> <p>Here is a small example showing use of ThreadLocal in java program and proving that every thread has it’s own copy of ThreadLocal variable.</p> <p><code>ThreadLocalExample.java</code></p> <!-- Quick Adsense WordPress Plugin: http://quickadsense.com/ --> <div style="float: none; margin:10px 0 10px 0; text-align:center;"> <div data-type="ad" data-publisher="journaldev.com" data-format="300x250" data-zone="jd_post_mid_300x250"></div> </div>php
<pre style="display: block;"><code class="hljs java"><div class="re_clip-board">Copy</div> <span class="hljs-keyword">package</span> com.journaldev.threads; <span class="hljs-keyword">import</span> java.text.SimpleDateFormat; <span class="hljs-keyword">import</span> java.util.Random; <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadLocalExample</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{ <span class="hljs-comment">// SimpleDateFormat is not thread-safe, so give one to each thread</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> ThreadLocal<SimpleDateFormat> formatter = <span class="hljs-keyword">new</span> ThreadLocal<SimpleDateFormat>(){ <span class="hljs-meta">@Override</span> <span class="hljs-function"><span class="hljs-keyword">protected</span> SimpleDateFormat <span class="hljs-title">initialValue</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> SimpleDateFormat(<span class="hljs-string">"yyyyMMdd HHmm"</span>); } }; <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{ ThreadLocalExample obj = <span class="hljs-keyword">new</span> ThreadLocalExample(); <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span> ; i<<span class="hljs-number">10</span>; i++){ Thread t = <span class="hljs-keyword">new</span> Thread(obj, <span class="hljs-string">""</span>+i); Thread.sleep(<span class="hljs-keyword">new</span> Random().nextInt(<span class="hljs-number">1000</span>)); t.start(); } } <span class="hljs-meta">@Override</span> <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{ System.out.println(<span class="hljs-string">"Thread Name= "</span>+Thread.currentThread().getName()+<span class="hljs-string">" default Formatter = "</span>+formatter.get().toPattern()); <span class="hljs-keyword">try</span> { Thread.sleep(<span class="hljs-keyword">new</span> Random().nextInt(<span class="hljs-number">1000</span>)); } <span class="hljs-keyword">catch</span> (InterruptedException e) { e.printStackTrace(); } <span class="hljs-comment">//formatter pattern is changed here by thread, but it won't reflect to other threads</span> formatter.set(<span class="hljs-keyword">new</span> SimpleDateFormat()); System.out.println(<span class="hljs-string">"Thread Name= "</span>+Thread.currentThread().getName()+<span class="hljs-string">" formatter = "</span>+formatter.get().toPattern()); } } </code></pre>html
<p>Output of the above java ThreadLocal example program is:</p> <!-- Quick Adsense WordPress Plugin: http://quickadsense.com/ --> <div style="float: none; margin:10px 0 10px 0; text-align:center;"> <div data-type="ad" data-publisher="journaldev.com" data-zone="jd_leaderboard_728x90" data-format="728x90"> </div> </div>java
<pre style="display: block;"><code class="hljs coffeescript"><div class="re_clip-board" style="display: none;">Copy</div> Thread Name= <span class="hljs-number">0</span> <span class="hljs-keyword">default</span> Formatter = yyyyMMdd HHmm Thread Name= <span class="hljs-number">1</span> <span class="hljs-keyword">default</span> Formatter = yyyyMMdd HHmm Thread Name= <span class="hljs-number">0</span> formatter = M/d/yy h:mm a Thread Name= <span class="hljs-number">2</span> <span class="hljs-keyword">default</span> Formatter = yyyyMMdd HHmm Thread Name= <span class="hljs-number">1</span> formatter = M/d/yy h:mm a Thread Name= <span class="hljs-number">3</span> <span class="hljs-keyword">default</span> Formatter = yyyyMMdd HHmm Thread Name= <span class="hljs-number">4</span> <span class="hljs-keyword">default</span> Formatter = yyyyMMdd HHmm Thread Name= <span class="hljs-number">4</span> formatter = M/d/yy h:mm a Thread Name= <span class="hljs-number">5</span> <span class="hljs-keyword">default</span> Formatter = yyyyMMdd HHmm Thread Name= <span class="hljs-number">2</span> formatter = M/d/yy h:mm a Thread Name= <span class="hljs-number">3</span> formatter = M/d/yy h:mm a Thread Name= <span class="hljs-number">6</span> <span class="hljs-keyword">default</span> Formatter = yyyyMMdd HHmm Thread Name= <span class="hljs-number">5</span> formatter = M/d/yy h:mm a Thread Name= <span class="hljs-number">6</span> formatter = M/d/yy h:mm a Thread Name= <span class="hljs-number">7</span> <span class="hljs-keyword">default</span> Formatter = yyyyMMdd HHmm Thread Name= <span class="hljs-number">8</span> <span class="hljs-keyword">default</span> Formatter = yyyyMMdd HHmm Thread Name= <span class="hljs-number">8</span> formatter = M/d/yy h:mm a Thread Name= <span class="hljs-number">7</span> formatter = M/d/yy h:mm a Thread Name= <span class="hljs-number">9</span> <span class="hljs-keyword">default</span> Formatter = yyyyMMdd HHmm Thread Name= <span class="hljs-number">9</span> formatter = M/d/yy h:mm a </code></pre>express
<p>As you can see from the output that Thread-0 has changed the value of formatter but still thread-2 default formatter is same as the initialized value. You can see the same pattern for other threads too.</p> <p><strong>Update</strong>: ThreadLocal class is extend in <a href="https://www.journaldev.com/2389/java-8-features-with-examples">Java 8</a> with a new method <code>withInitial()</code> that takes Supplier functional interface as argument. So we can use lambda expressions to easily create the ThreadLocal instance. For example, above formatter ThreadLocal variable can be defined in one line as below:</p> <pre style="display: block;"><code class="hljs coffeescript"><div class="re_clip-board" style="display: none;">Copy</div> private static final ThreadLocal<SimpleDateFormat> formatter = ThreadLocal.<SimpleDateFormat>withInitial (<span class="hljs-function"><span class="hljs-params">()</span> -></span> {<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> SimpleDateFormat(<span class="hljs-string">"yyyyMMdd HHmm"</span>);}); </code></pre> <p>If you are new to Java 8 features, please check out <a href="https://www.journaldev.com/2389/java-8-features-with-examples" title="Java 8 Features">Java 8 Features</a> and <a href="https://www.journaldev.com/2763/java-8-functional-interfaces" title="Java 8 Functional Interfaces">Java 8 Functional Interfaces</a>.</p> <p>That’s all for ThreadLocal in java programming.</p> <!-- Quick Adsense WordPress Plugin: http://quickadsense.com/ --> <div style="float: none; margin:10px 0 10px 0; text-align:center;"> <!-- CM_JD_AP_Middle_Responsive --> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-5143693538742787" data-ad-slot="7174295726" data-ad-format="auto"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div>api
<p>Reference: <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/ThreadLocal.html" rel="noopener" target="_blank">API Doc</a></p>oracle
<!-- Quick Adsense WordPress Plugin: http://quickadsense.com/ -->less
<div style="float: none; margin:0px 0 0px 0; text-align:center;"> <script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5143693538742787" data-ad-slot="3941417857"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div>dom
<div style="font-size: 0px; height: 0px; line-height: 0px; margin: 0; padding: 0; clear: both;"></div><div class="scriptlesssocialsharing"><div class="scriptlesssocialsharing-buttons"><a class="button twitter" target="_blank" href="https://twitter.com/intent/tweet?text=Java%20ThreadLocal%20Example&url=https%3A%2F%2Fwww.journaldev.com%2F1076%2Fjava-threadlocal-example&via=JournalDev&related=JournalDev" rel="noopener"><span class="sss-name">Twitter</span></a><a class="button facebook" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.journaldev.com%2F1076%2Fjava-threadlocal-example" rel="noopener"><span class="sss-name">Facebook</span></a><a class="button linkedin" target="_blank" href="https://www.linkedin.com/shareArticle?mini=1&url=https%3A%2F%2Fwww.journaldev.com%2F1076%2Fjava-threadlocal-example&title=Java%20ThreadLocal%20Example&source=https://www.journaldev.com" rel="noopener"><span class="sss-name">Linkedin</span></a><a class="button email" target="_blank" href="mailto:?body=I%20read%20this%20post%20and%20wanted%20to%20share%20it%20with%20you.%20Here's%20the%20link:%20https%3A%2F%2Fwww.journaldev.com%2F1076%2Fjava-threadlocal-example&subject=A%20post%20worth%20sharing:%20Java%20ThreadLocal%20Example" rel="noopener"><span class="sss-name">Email</span></a></div></div><div class="prev-next-navigation"><a href="https://www.journaldev.com/1072/daemon-thread-in-java" rel="prev"><div class="previous"><span class="prev_icon"> Previous </span><br> <span class="pagi_content">Daemon Thread in Java</span></div></a><a href="https://www.journaldev.com/1079/multithreading-in-java" rel="next"><div class="next"><span class="next_icon">Next </span><br> <span class="pagi_content">Multithreading in Java</span></div></a></div> <!-- .prev-next-navigation --><section class="author-box" itemprop="author" itemscope="" itemtype="https://schema.org/Person"><h4 class="author-box-title">About <span itemprop="name">Pankaj</span></h4><div class="author-box-content" itemprop="description"><p>If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on <a href="https://plus.google.com/118104420597648001532/posts?rel=author"><strong>Google Plus</strong></a>, <a href="https://www.facebook.com/journaldev"><strong>Facebook</strong></a> or <a href="https://twitter.com/JournalDev"><strong>Twitter</strong></a>. I would love to hear your thoughts and opinions on my articles directly.</p> <p>Recently I started creating video tutorials too, so do check out my videos on <a href="https://www.youtube.com/user/JournalDev"><strong>Youtube</strong></a>.</p> </div></section></div>async