threads

ThreadLocal example

With this example we are going to demonstrate how to create a ThreadLocal. The ThreadLocal class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread. In short, to create a ThreadLocal you should:

  • Create a ThreadLocal variable.
  • Return the value in the current thread’s copy of this thread-local variable to an Object, using get() API method of ThreadLocal.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;

public class ThreadLocalExmp {

    public static void main(String[] argv) throws Exception {

  ThreadLocal lThread = new ThreadLocal();

  Object obj = lThread.get();

  lThread.set(obj);

    }
}

  
This was an example of how to create a ThreadLocal in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button