Object usage and sharing: ThreadLocal

1 Introduction

There are four common strategies for using and sharing objects in a multithreaded environment :

  1. Thread Enclosure : A thread-enclosed object can only be owned by a thread, a thread is enclosed in a thread, and can only be modified by this thread. The implementation techniques are ==stack closure== andThreadLocal==== classes;
  2. Read-only sharing: Allows read-only and unmodifiable objects to be concurrently accessed by multiple threads safely. Implementation techniques for such strategies as immutable objects and de facto immutable objects;
  3. Protect objects: use a specific lock to access objects;
  4. Thread-safe sharing: Synchronize inside objects, and only use common interfaces to provide access to object state - not very well understood.
2. ThreadLocalBasic idea

One of the ways to achieve thread closure is stack closure . Objects can only be accessed through local variables, and local variables are enclosed in the executing thread and cannot be modified by other threads. Another blog post explains it.

advantage

ThreadLocalThere is an independent copy for each thread that uses the variable , so each thread's modification to this variable is only in its own working memory, and there is no time overhead for synchronizing memory. Therefore, it can also be said that stack closure trades space for time and security.

scenes to be used

ThreadLocal should be used if the object has a particularly high allocation overhead or is executed very frequently in a thread.

3. Implementation
main method
  • T iniinitialValue(): Initialize the current thread copy value;
  • T get(): Returns the copy value of the thread-local variable in this thread. If the current thread does not have a corresponding copy value, the iniinitialValuemethod will be called to return;
  • set(T value): Set the current thread copy value;
  • remove(): Removes the current thread-local variable copy value.

Example:

public class ThreadLocalDemo implements Runnable {

    private static ThreadLocal<Integer> threadLocalVal=new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 1;
        }
    };
    
    public Integer getThreadLocalVal() {
        return threadLocalVal.get();//fixme 返回的只是Integer变量的副本而已
    }

    @Override
    public void run() {
        Integer i=threadLocalVal.get();
        while(true){
            System.out.println(i++);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new ThreadLocalDemo()).start();
        new Thread(new ThreadLocalDemo()).start();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325163666&siteId=291194637