Saturday, September 27, 2014

ThreadLocal

import java.util.HashMap;
import java.util.Map;

public class CustomThreadLocal {

    private static Map threadMap = new HashMap();

    public static void add(Object object) {
        threadMap.put(Thread.currentThread(), object);
    }

    public static void remove(Object object) {
        threadMap.remove(Thread.currentThread());
    }

    public static Object get() {
        return threadMap.get(Thread.currentThread());
    }

}


public class hreadLocalMainSampleEx1 {

    public static void main(String[] args) {
        new Thread(new Runnable() {
            public void run() {
                ThreadContext threadContext = new ThreadContext();
                threadContext.setTransactionId(1l);
                threadContext.setUserId("User 1");
                CustomThreadLocal.add(threadContext);
                //here we call a method where the thread context is not passed as parameter
                PrintThreadContextValues.printThreadContextValues();
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                ThreadContext threadContext = new ThreadContext();
                threadContext.setTransactionId(2l);
                threadContext.setUserId("User 2");
                CustomThreadLocal.add(threadContext);
                //here we call a method where the thread context is not passed as parameter
                PrintThreadContextValues.printThreadContextValues();
            }
        }).start();
    }
}

public class PrintThreadContextValues {
    public static void printThreadContextValues(){
        System.out.println(CustomThreadLocal.get());
    }
}

public class ThreadContext {

    private String userId;

    private Long transactionId;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public Long getTransactionId() {
        return transactionId;
    }

    public void setTransactionId(Long transactionId) {
        this.transactionId = transactionId;
    }

    public String toString() {
        return "userId:" + userId + ",transactionId:" + transactionId;
    }

}

No comments:

Post a Comment