(2) Random v.s. ThreadLocalRandom

About

๋ฐ”๋กœ ์ด์ „ ๊ธ€ (1) Math.random() v.s. Random์—์„œ java.lang.Math.random()๊ณผ java.util.Random์˜ ์ฐจ์ด๋ฅผ ์•Œ์•„๋ณด์•˜๋‹ค. ๋‘˜ ์ค‘์—์„œ๋Š” ํ›„์ž๋ฅผ ์“ฐ์ž๋Š” ๊ฒƒ์œผ๋กœ ๊ฒฐ๋ก ์„ ๋‚ด๋ ธ๋Š”๋ฐ, Random๋„ ์„ฑ๋Šฅ ์ƒ์˜ ๋ฌธ์ œ๊ฐ€ ์žˆ๋‹ค. ์ด๋ฒˆ์—” ThreadLocalRandom์„ ์•Œ์•„๋ณด์ž.

java.util.Random

Java 1.0๋ถ€ํ„ฐ ์กด์žฌํ–ˆ๋‹ค. Thread-safeํ•˜์ง€๋งŒ ์—ฌ๋Ÿฌ ์“ฐ๋ ˆ๋“œ์—์„œ ๋™์‹œ ์ ‘๊ทผํ•˜๋ฉด ๊ฒฝํ•ฉ์ด ๋ฐœ์ƒํ•˜์—ฌ ์„ฑ๋Šฅ์ด ์ €ํ•˜๋œ๋‹ค.

java.util.concurrent.ThreadLocalRandom

ThreadLocalRandom์€ ์“ฐ๋ ˆ๋“œ๋ณ„๋กœ ๊ฒฉ๋ฆฌ๋œ ๋‚œ์ˆ˜์ƒ์„ฑ๊ธฐ(Random Number Generator)์ด๋‹ค.

Random๋„ thread-safeํ•˜๊ณ  ThreadLocalRandom๋„ thread-safeํ•˜์ง€๋งŒ ์ด์œ ๊ฐ€ ๋‹ค๋ฅด๋‹ค.

  • Random์€ seed๋ฅผ AtomicLong์„ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ, ๋ฉ€ํ‹ฐ์“ฐ๋ ˆ๋“œ ์š”์ฒญ์— ๋Œ€ํ•ด์„œ๋„ ์ˆœ์„œ๋Œ€๋กœ ์ฒ˜๋ฆฌํ•ด ๋งˆ์น˜ ๋™๊ธฐํ™”(synchronized) ์ฒ˜๋ฆฌ์ฒ˜๋Ÿผ ๋™์ž‘ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋Š๋ฆฌ๋‹ค. (๋™๊ธฐํ™” ๋ฐฉ์‹์ฒ˜๋Ÿผ ๋™์ž‘ํ•˜๋ฏ€๋กœ thread-safeํ•˜๋‹ค.)

  • ThreadLocalRandom์€ AtomicLong์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , ์“ฐ๋ ˆ๋“œ๋ณ„๋กœ seed๊ฐ’์„ ๋‹ค๋ฅด๊ฒŒ ๊ด€๋ฆฌํ•˜๋ฏ€๋กœ Random๋ณด๋‹ค ์“ฐ๋ ˆ๋“œ์— ๋Œ€ํ•ด ์‘๋‹ต์ด ๋น ๋ฅด๊ณ  thread-safeํ•˜๋‹ค.

๊ฒฐ๋ก : JDK 7๋ถ€ํ„ฐ Random์„ ์‚ฌ์šฉํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค. ThreadLocalRandom์„ ์“ฐ๋ฉด ๋œ๋‹ค.

Code

ThreadLocalRandomTest.java
import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomTest {
    public static void main(String[] args) {
        int rand = ThreadLocalRandom.current().nextInt(100);
        System.out.println(rand); // 99
    }
}

+ java.util.SplittableRandom

SplittableRandom์€ ๊ฒฉ๋ฆฌ๋œ ๋ณ‘๋ ฌ์ฒ˜๋ฆฌ์— ํŠนํ™”๋œ ๋‚œ์ˆ˜์ƒ์„ฑ๊ธฐ์ด๋‹ค.

  • Thread-safeํ•˜์ง€ ์•Š์œผ๋ฏ€๋กœ ์ฃผ์˜๊ฐ€ ํ•„์š”ํ•˜๋‹ค.

  • ํŠน์ • ์ƒํ™ฉ์—์„œ๋Š” ThreadLocalRandom๋ณด๋‹ค ์œ ๋ฆฌํ•˜๋‹ค.

  • ํ•ด๋‹น ๋‚ด์šฉ์€ REF๋ฅผ ์ฐธ๊ณ ํ•˜์ž.

More on the matter

REF

Last updated