SecurityContextHolder ThreadLocal

Knowing SecurityContextHolder using ThreadLocal to store user related information. Meaning it does not use HttpSession due to some security concern (not discuss here). Wrote a main method to test that out.

public class NormalThreadExample {

    public class MyThread implements Runnable {

        private Integer normalInteger;

        @Override
        public void run() {
            try {
                Integer randomInt = (int) (Math.random() * 999);
                System.out.println(Thread.currentThread().getName() + " SET " + randomInt);
                normalInteger = randomInt;
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + " GET " + normalInteger);

            } catch (InterruptedException ex) {
                // SOME HANDLER
            }
        }
    }

    public void haveFun() throws InterruptedException{
        MyThread myThread = new MyThread();
        Thread thread1 = new Thread(myThread);
        Thread thread2 = new Thread(myThread);
        thread1.start();
        thread2.start();

    }
    
    public static void main(String[] args) throws InterruptedException {
        NormalThreadExample example = new NormalThreadExample();
        example.haveFun();
    }
}
//Output : 
Thread-0 SET 737
Thread-1 SET 404
Thread-1 GET 404
Thread-0 GET 404
public class ThreadLocalExample {

    public class MyThread implements Runnable {
        
        private ThreadLocal<Integer> threadLocalInteger = new ThreadLocal<>();
        
        @Override
        public void run() {
            try {
                Integer randomInt = (int) (Math.random() * 999);
                System.out.println(Thread.currentThread().getName() + " SET " + randomInt);
                threadLocalInteger.set(randomInt);
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + " GET " + threadLocalInteger.get());
            } catch (InterruptedException ex) {
                // SOME HANDLER
            }
        }
    }

    public void haveFun() throws InterruptedException{
        MyThread myThread = new MyThread();
        Thread thread1 = new Thread(myThread);
        Thread thread2 = new Thread(myThread);
        thread1.start();
        thread2.start();
    }
    
    public static void main(String[] args) throws InterruptedException {
        ThreadLocalExample example = new ThreadLocalExample();
        example.haveFun();
    }
}
//Output
Thread-0 SET 3
Thread-1 SET 860
Thread-1 GET 860
Thread-0 GET 3

Note: Output result may be vary since it’s using random generator.

 

dicksonkho

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.