ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Threadlocal
    StaticPL/JAVA 2019. 8. 19. 22:28

    1. Overview

    Clarify what Threadlocal is and how and when to use it.

     

    2. Introduction

    Threadlocal has the ability to store data individually for the current thread. Thus, even if multiple threads are executing the same code, and the code has a reference to a Threadlocal variable, there's no need to synchronize that variable because multiple threads cannot see each other's Threadlocal variables.

     

    3. Usages

     

    public class ThreadLocalExample {
    
    
        public static class MyRunnable implements Runnable {
    
            private ThreadLocal<Integer> threadLocal =
                   new ThreadLocal<Integer>();
    
            @Override
            public void run() {
                threadLocal.set( (int) (Math.random() * 100D) );
        
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                }
        
                System.out.println(threadLocal.get());
            }
        }
    
    
        public static void main(String[] args) {
            MyRunnable sharedRunnableInstance = new MyRunnable();
    
            Thread thread1 = new Thread(sharedRunnableInstance);
            Thread thread2 = new Thread(sharedRunnableInstance);
    
            thread1.start();
            thread2.start();
    
            thread1.join(); //wait for thread 1 to terminate
            thread2.join(); //wait for thread 2 to terminate
        }
    
    }

    thread1, thread2 both execute the run() method, thus different values are set on each Threadlocal instance. if these aren't Threadlocal object and set() had been synchronized, the thread2 would have overridden the value set by the thread1.

     

    4. References

    http://tutorials.jenkov.com/java-concurrency/threadlocal.html

    'StaticPL > JAVA' 카테고리의 다른 글

    Executors Framework and Thread Pools  (0) 2019.08.21
    CompletableFuture, and Future  (0) 2019.08.20
    Thread and Runnable  (0) 2019.08.18
    Stream  (0) 2019.08.18
    Difference between Abstract Class and Interface  (0) 2019.08.18

    댓글

Designed by Tistory.