Thread Local

Java Thread Local์€ ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„œ ๊ฐ ์Šค๋ ˆ๋“œ์—์„œ ๊ณ ์œ ํ•œ ๊ฐ’์„ ๊ฐ€์ง€๋„๋ก ํ•˜๋Š” ๊ธฐ๋Šฅ์ž…๋‹ˆ๋‹ค. ์ด๋ฅผ ํ†ตํ•ด ์—ฌ๋Ÿฌ ์Šค๋ ˆ๋“œ์—์„œ ๊ณต์œ ๋˜๋Š” ๊ฐ์ฒด์— ๋Œ€ํ•œ ๋™์‹œ ์ ‘๊ทผ ๋ฌธ์ œ๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์‚ฌ์šฉ ๋ฐฉ๋ฒ•

Thread Local์„ ์‚ฌ์šฉํ•˜๋ ค๋ฉด java.lang ํŒจํ‚ค์ง€์˜ ThreadLocal ํด๋ž˜์Šค๋ฅผ ์ด์šฉํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๊ฐ ์Šค๋ ˆ๋“œ์—์„œ ๊ณ ์œ ํ•œ ๊ฐ’์„ ๊ฐ€์ง€๋„๋ก ํ•˜๋ ค๋Š” ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•œ ๋‹ค์Œ, ThreadLocal ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜์—ฌ ํ•ด๋‹น ๊ฐ์ฒด๋ฅผ ์ €์žฅํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

public class MyThreadSafeClass {
    private ThreadLocal<Integer> threadLocalValue = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    public void incrementValue() {
        threadLocalValue.set(threadLocalValue.get() + 1);
    }

    public int getValue() {
        return threadLocalValue.get();
    }
}

์œ„์˜ ์ฝ”๋“œ์—์„œ๋Š” MyThreadSafeClass ํด๋ž˜์Šค ๋‚ด๋ถ€์—์„œ ThreadLocal ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜์—ฌ Integer ๊ฐ’์„ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. initialValue() ๋ฉ”์†Œ๋“œ๋ฅผ ์˜ค๋ฒ„๋ผ์ด๋“œํ•˜์—ฌ, ์Šค๋ ˆ๋“œ๊ฐ€ ๊ฐ’์— ์ฒ˜์Œ์œผ๋กœ ์ ‘๊ทผํ•  ๋•Œ 0์„ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.

incrementValue() ๋ฉ”์†Œ๋“œ๋Š” Thread Local์— ์ €์žฅ๋œ ๊ฐ’์„ ์ฆ๊ฐ€์‹œํ‚ค๊ณ , getValue() ๋ฉ”์†Œ๋“œ๋Š” Thread Local์— ์ €์žฅ๋œ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ๊ตฌํ˜„ํ•˜๋ฉด ์—ฌ๋Ÿฌ ์Šค๋ ˆ๋“œ์—์„œ MyThreadSafeClass ๊ฐ์ฒด๋ฅผ ๊ณต์œ ํ•˜๋”๋ผ๋„ ๊ฐ ์Šค๋ ˆ๋“œ์—์„œ๋Š” ๊ณ ์œ ํ•œ ๊ฐ’์„ ๊ฐ€์ง€๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

ํ™œ์šฉ ์˜ˆ์‹œ

Thread Local์€ ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„œ ๋งŽ์ด ์‚ฌ์šฉ๋˜๋Š” ๊ธฐ๋Šฅ ์ค‘ ํ•˜๋‚˜์ž…๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ ๊ฐ ์š”์ฒญ๋งˆ๋‹ค ๋กœ๊ทธ์ธํ•œ ์‚ฌ์šฉ์ž ์ •๋ณด๋ฅผ ์œ ์ง€ํ•˜๊ณ  ์‹ถ์„ ๋•Œ Thread Local์„ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

public class UserContext {
    private static final ThreadLocal<User> userThreadLocal = new ThreadLocal<>();

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

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

์œ„์˜ ์ฝ”๋“œ์—์„œ๋Š” UserContext ํด๋ž˜์Šค ๋‚ด๋ถ€์—์„œ Thread Local์„ ์ด์šฉํ•˜์—ฌ ๋กœ๊ทธ์ธํ•œ ์‚ฌ์šฉ์ž ์ •๋ณด๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. ๊ฐ ์š”์ฒญ๋งˆ๋‹ค UserContext.setUser() ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ๋กœ๊ทธ์ธํ•œ ์‚ฌ์šฉ์ž ์ •๋ณด๋ฅผ ์ €์žฅํ•˜๋ฉด, ํ•ด๋‹น ์š”์ฒญ์—์„œ๋Š” UserContext.getUser() ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ๋กœ๊ทธ์ธํ•œ ์‚ฌ์šฉ์ž ์ •๋ณด๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

Java Thread Local์€ ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„œ ๊ณต์œ  ๋ณ€์ˆ˜์— ๋Œ€ํ•œ ๋™์‹œ ์ ‘๊ทผ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐ์—์— ์œ ์šฉ

Last updated