AtomicLong
AtomicLong๋
- ์๋ฐ์์ ์ ๊ณตํ๋ ํด๋์ค๋ก ๋ฉํฐ ์ค๋ ๋ ํ๊ฒฝ์์ ์์์ ์ผ๋ก ์ฐ์ฐ์ ์ํํ ์ ์๋๋ก ๋์์ค๋ค.
java.util.concurrent.atomicํจํค์ง์์ ์ ๊ณต์ ํ๋ฉฐ,AtomicInteger, AtomicBoolean, AtomiceReference๋ฑ ๋ค๋ฅธ ์๋ฃํ์ ๋ํด์๋ ํด๋์ค๋ฅผ ์ ๊ณตํ๋ค.Atomic, ์์๋ฅผ ์๋ฏธํ๋ฉฐ, ๊ฐ ์ฐ์ฐ์ ์ธ๋ถ์ ์ํฅ์ ๋ฏธ์น์ง ์๊ณ ์์์ ์ผ๋ก ์ํํ ์ ์๋ค.- lock์ ๊ฑธ์ง ์๊ณ ๋์์ฑ ํ๊ฒฝ์ ํด๊ฒฐํ๋ ์๊ณ ๋ฆฌ์ฆ์ ๋ฐ์ดํฐ ๋ฌด๊ฒฐ์ฑ์ ๋ณด์ฅํ๊ธฐ ์ํ CAS ์ฐ์ฐ์ ์ ์ฉํ๋ค๊ณ ํ๋ค.
- AtomicLong์ ๊ฐ์ ํด๋์ค์๋ ํด๋น ์ฐ์ฐ์ด ์ ์ฉ๋๋ค๊ณ ํ๋ค.
์ฆ๊ฐ์ฐ์ฐ์์ ์ฐจ์ด์
- userId++๊ณผ ๊ฐ์ ์ฆ๊ฐ ์ฐ์ฐ์๋ ์ฑ๊ธ ์ค๋ ๋ ํ๊ฒฝ์์๋ ์ ์์ ์ผ๋ก ๋์ํ์ง๋ง, ์ ์ ์ค๋ ๋๊ฐ ๋ง์์ง๋ฉด ๊ธฐ๋ํ ๊ฐ์ ํ์ธํ๊ธฐ ์ด๋ ค์์ง๋ค.
- ๊ทธ ์ด์ ๋
++์ ๊ฐ์ ์ฆ๊ฐ์ฐ์ฐ์ ๋ก์ง ๋๋ฌธ์ด๋ผ๊ณ ํ๋ค.- userId์ ๊ฐ์ ์ป๋๋ค.
- userId์ ๊ฐ์ ์ฆ๊ฐ์ํจ๋ค.
- ์ฆ๊ฐ๋ userId์ ๊ฐ์ ๊ธฐ์กด ๋ฉ๋ชจ๋ฆฌ์ ๋ค์ ์ด๋ค.
- ๋ง์ฝ, ๋ ๊ฐ์ ์ค๋ ๋์์ userId++ ์ฐ์ฐ์ ์ํํ๊ฒ ๋๋ฉด, ์ด๊ธฐ์ ๋์ผํ ๊ฐ์ ์ป๊ณ ๊ฐ๊ฐ ์ฆ๊ฐ์ํค๊ธฐ ๋๋ฌธ์ ๊ธฐ๋๊ฐ๋ณด๋ค ์ ๊ฒ ์ฆ๊ฐํ ์ ์๋ค.
- A์ B๊ฐ userId = 6์ ๊ฐ์ ์ฆ๊ฐ์ฐ์ฐ์ผ๋ก ์ฆ๊ฐ์ํฌ๋ ค๊ณ ํ๋ค.
- ์ด๊ธฐ์ ๋์ผํ ๊ฐ 6์ ๊ฐ์ ธ์ค๊ฒ ๋๊ณ ๊ฐ๊ฐ ์ฆ๊ฐ์ํจ๋ค.
- ๊ทธ๋ฌ๋ฉด A์ B๋ ๋์ผํ๊ฒ 7์ด๋ผ๋ ๊ฐ์ ๊ฐ์ง๊ฒ ๋๋ค.
- A์ B๊ฐ ๊ฐ์ ์ฆ๊ฐ์์ผฐ๊ธฐ ๋๋ฌธ์ userId๋ 8์ด๋ผ๋ ๊ฐ์ ๊ฐ์ ธ์ผํ์ง๋ง, ๊ฒฐ๊ณผ์ ์ผ๋ก๋ 7์ด๋ผ๋ ๊ฐ์ ๊ฐ์ง๊ฒ ๋๋ค.
- ์ด๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด
synchronizedํค์๋๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ๋ ์กด์ฌํ๋ค.- ๋ค๋ง ์ด ๋ฐฉ๋ฒ์ ์ฌ์ฉํ๊ฒ ๋๋ฉด, ํ๋์ ์ค๋ ๋๊ฐ lock๋ฅผ ๊ฑธ๊ณ ์ฐ์ฐ์ ์ํํ ๋, ๋ค๋ฅธ ์ค๋ ๋๋ lock์ด ํ๋ฆด ๋ ๊น์ง ๊ธฐ๋ฌ๋ ค์ผ ํ๋ค.
- ๋ค๋ฅธ ์ผ์ ํ์ง ๋ชปํ๊ณ ๊ณ์ ๊ธฐ๋ค๋ ค์ผ ํ๊ธฐ ๋๋ฌธ์ ์ฑ๋ฅ์ ํ๊ฐ ๋ฐ์ํ ์ ์๋ค.
ํ ์คํธ
@Test
void addTest() throws InterruptedException {
Counter counter = new Counter();
int threadCount = 10000;
ExecutorService executorService = Executors.newFixedThreadPool(32);
CountDownLatch countDownLatch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
executorService.submit(() - > {
try {
counter.increment();
} finally {
countDownLatch.countDown();
}
});
}
countDownLatch.await();
executorService.shutdown();
assertEquals(threadCount, counter.getCount());
}
public static class Counter {
int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
- int ์๋ฃํ์ผ๋ก ๋ณ์๋ฅผ ์ฌ์ฉํ ๋ ค ํ์ผ๋, ์ค๋ ๋๊ฐ ๊ณต์ ๊ฐ ๋์ง ์์ Atomic ํด๋์ค๋ฅผ ์ฌ์ฉํ๋ผ๊ณ ๋ฌธ๊ตฌ๊ฐ ๋์๋ค.
- ์์ ์ฆ๊ฐ ์ฐ์ฐ์๋ง ์ฌ์ฉํด์ ํ ์คํธ๋ฅผ ์งํํ๊ณ ์ถ๊ธฐ ๋๋ฌธ์, Counter๋ผ๋ ํด๋์ค๋ฅผ ์ ์ธํด์ ํ ์คํธ๋ฅผ ์งํํ๋ค.
- ํ ์คํธ ๊ฒฐ๊ณผ๋ ๋ค์๊ณผ ๊ฐ๋ค.

- ์ค๋ ๋์ ๊ฐ์๊ฐ ์ ์ ๋๋ ํต๊ณผ๋ฅผ ํ์ง๋ง, ์ค๋ ๋์ ๊ฐ์๊ฐ ์ฆ๊ฐํ๋ฉด ์ ์ ๊ธฐ๋๊ฐ๋ณด๋ค ์ ์ ๊ฐ์ด ๋์จ๋ค.
public synchronized void increment() {
count++;
}
synchronizedํค์๋๋ฅผ ์ฌ์ฉํด์ ํ ์คํธ๋ฅผ ์งํํด๋ดค๋ค.- ํ ์คํธ ๊ฒฐ๊ณผ๋ ๋ค์๊ณผ ๊ฐ๋ค.

- ์ฑ๋ฅ ์ ํ๊ฐ ๋ฐ์ํ๋ค๊ณ ํ๋๋ฐ, ํ
์คํธ ์ฝ๋ ์คํ์๊ฐ์์ ํฐ ์ฐจ์ด๊ฐ ๋์ง ์์๋ค.
- ํ
์คํธ ์ฝ๋๋ฅผ ์๋ชป ์์ฑํ๊ฑด๊ฐ..?