TransmittableThreadLocal in Java

https://github.com/alibaba/transmittable-thread-local

On the one hand

Once upon a time, in a futuristic world where advanced technologies and intergalactic travels were the norms, there existed a special framework known as TransmittableThreadLocal. This innovative creation was conceived to overcome the limitations of traditional thread-based communication and enable seamless data transmission across multiple dimensions.

In this far-flung universe, different entities, known as threads, roamed tirelessly in parallel, each possessing its unique state and data. However, these threads faced a challenge when they needed to communicate and share information with each other. Existing solutions, such as ordinary ThreadLocal, proved ineffective in bridging the gap between threads that traversed through wormholes or delved into the depths of cosmic thread pools.

TransmittableThreadLocal, with its revolutionary design, introduced a breakthrough concept. It harnessed the power of teleportation, allowing data values to be teleported along with the threads themselves. As these threads embarked on their interstellar journeys, TransmittableThreadLocal ensured that the transmitted values stayed intact and consistent across the vast expanse of space and time.

Through the magic of TransmittableThreadLocal, threads engaged in collaborative endeavors, seamlessly passing on information and knowledge as they explored uncharted territories. Whether it was a distant galaxy or a parallel universe, threads could rely on TransmittableThreadLocal to always carry the right data with them, making their interactions more meaningful and efficient.

In the grand cosmic dance of processing, tasks flowed effortlessly between thread pools, with TransmittableThreadLocal acting as the universal communicator. It ensured that data, like the cosmic energies, remained synchronized throughout the intricate network of computations and transformations, defying the limitations of traditional thread-based communication.

With TransmittableThreadLocal, the inhabitants of this science fiction realm unlocked incredible potential for advanced artificial intelligence, predictive analytics, and parallel processing. The universe witnessed a paradigm shift in the way threads collaborated, as the bounds of traditional thread communication were shattered by the power of teleportation and consistency.

Simply put

TransmittableThreadLocal is a thread-level variable in Java that allows values to be transmitted and maintained consistently between threads. Unlike a regular ThreadLocal, TransmittableThreadLocal can correctly propagate values in thread pools and asynchronous tasks, ensuring that the correct variable values are accessible during task execution.

To use TransmittableThreadLocal, you’ll need to include the com.alibaba:transmittable-thread-local dependency in your project and use the TransmittableThreadLocal class provided by it.

Here’s an example of how to use TransmittableThreadLocal:

import com.alibaba.ttl.TransmittableThreadLocal;

public class Example {
    private static ThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();

    public static void main(String[] args) {
        threadLocal.set("Hello World");

        Runnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();

        // Wait for the child thread to finish its execution
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("main thread: " + threadLocal.get()); // Output: main thread: Hello World
    }

    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("child thread: " + threadLocal.get()); // Output: child thread: Hello World
        }
    }
}

In the above code, we first create a TransmittableThreadLocal variable called threadLocal and set its value in the main thread. Then, we create a child thread and start it. In the child thread, we use threadLocal.get() to access the correct value set in the main thread. Finally, in the main thread, we also use threadLocal.get() to access the correct value.

In summary, TransmittableThreadLocal ensures the proper propagation of variable values in scenarios like thread pools and asynchronous tasks, guaranteeing the accessibility of the correct values during task execution.

使用 ME

		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>transmittable-thread-local</artifactId>
            <version>2.14.2</version>
        </dependency>

package com.patience.business.thread;

import com.alibaba.ttl.TransmittableThreadLocal;

/**
 * @author Green.Gee
 * @date 2023/7/21 17:28
 * @email [email protected]
 */
public class TransmittableThreadLocalExample {

    /**
     * TransmittableThreadLocal是一个线程级别的变量,它可以在线程之间传递并保持一致性。
     * 与普通的ThreadLocal不同的是,TransmittableThreadLocal可以在线程池和异步任务中正确传递值,
     * 保证任务执行时,能够访问到正确的变量值。
     * 使用TransmittableThreadLocal需要引入com.alibaba:transmittable-thread-local依赖,
     * 并使用它提供的TransmittableThreadLocal类。
     */
    public static void main(String[] args) {
        UserService.createUser("Alice");
        UserService.updateUser("Bob");
        UserService.deleteUser();

    }


    // mutil thread
    public static void transmittableThreadLocalUsages() {
        var context = new TransmittableThreadLocal<>();

        context.set("geeOS");
        System.err.println("[parent thread] set " + context.get());

        // new one thread
        new Thread(new Runnable() {
            @Override
            public void run() {
                var result = context.get();
                System.err.println("[one child thread] get " + result);

                context.set("OS");

            }
        }).start();

        // new sec thread
        new Thread(new Runnable() {
            @Override
            public void run() {
                var result = context.get();
                System.err.println("[sec child thread] get " + result);
            }
        }).start();

        System.err.println("[parent thread] get " + context.get());
    }

}


class UserHolder {
    private static ThreadLocal<String> userThreadLocal = new TransmittableThreadLocal<>();

    public static void setUser(String user) {
        userThreadLocal.set(user);
    }

    public static String getUser() {
        return userThreadLocal.get();
    }

    public static void removeUser() {
        userThreadLocal.remove();
    }
}


class UserService {
    public static void createUser(String user) {
        UserHolder.setUser(user);
        // 进行创建用户的逻辑处理
        System.out.println("Create user: " + UserHolder.getUser());

        // 在其他方法中继续使用UserHolder.getUser()来获取用户信息
    }

    public static void updateUser(String user) {
        UserHolder.setUser(user);
        // 进行更新用户的逻辑处理
        System.out.println("Update user: " + UserHolder.getUser());

        // 在其他方法中继续使用UserHolder.getUser()来获取用户信息
    }

    public static void deleteUser() {
        String user = UserHolder.getUser();
        // 进行删除用户的逻辑处理
        System.out.println("Delete user before: " + user);

        UserHolder.removeUser();

        System.out.println("Delete user after: " + UserHolder.getUser());

    }
}



你可能感兴趣的:(JavaBasic,knowledge,&,ME,&,GPT,java)