Discuss / Java / 写了一个通用的Threadlocal,供大家参考。

写了一个通用的Threadlocal,供大家参考。

Topic source

野路

#1 Created at ... [Delete] [Delete and Lock User]
// 可以是任意对象
```java
@Data
class User {
	private String name;
	private String sex;

// 具体封装的类

public class AutoCloseThreadLocal<T> implements AutoCloseable{
    private ThreadLocal<T> threadLocal = new ThreadLocal<>();
    
    public AutoCloseThreadLocal (T t) {
        threadLocal.set(t);
    }
    
    public void set(T value) {
        threadLocal.set(value);
    }

    public T get() {
        return threadLocal.get();
    }

    public void remove() {
        threadLocal.remove();
    }
    
    @Override
    public void close () throws Exception {
        threadLocal.remove();
        
    }
}

// 调用

public static void main (String[] args) {
		User u = new User();
		u.setAge(10);
		u.setName("Bob");
		u.setSex("男");
		try (var ctx = new AutoCloseThreadLocal(u)) {
			String value = ctx.get().toString();
			System.out.println(value);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

有问题请指正


  • 1

Reply