compare-and-swap

  • ์ผ๋ช… CAP

  • atomic instruction used in multi-threading to achieve synchronization

  • ํŠน์ • ๊ฐ’์ด (false), ์˜ˆ์ƒํ•œ ๊ฐ’ (false) ๊ณผ ๊ฐ™๋‹ค๋ฉด ์ƒˆ๋กœ์šด ๊ฐ’์œผ๋กœ ์น˜ํ™˜ํ•˜๋Š” ๋ฐฉ๋ฒ•.

  • ๋งŒ์•ฝ์— ํŠน์ • ๊ฐ’์ด (true), ์˜ˆ์ƒํ•œ ๊ฐ’(false) ๊ณผ ๋‹ค๋ฅด๋ฉด ํ•ด๋‹น ์น˜ํ™˜์ž‘์—…์€ ์‹คํŒจํ•จ์ด ๋ณด์žฅ๋จ.

code

  • java8

  • java.util.concurrent.atomic.AtomicInteger#incrementAndGet

    // sun.misc.Unsafe#getAndAddInt
    public final int getAndAddInt(Object var1, long var2, int var4) {
        int var5;
        do {
            var5 = this.getIntVolatile(var1, var2);
        } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));

        return var5;
    }
  • var5 ๋Š” volatile value

    • ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฑด ์ดˆ๊ธฐ๊ฐ’ (e.g = 1)

  • val1 ๋Š” AtomicInteger ํด๋ž˜์Šค

  • var2 ๋Š” valueOffSet

    • The offset is just used to determine which memory location to address when updating the value field of AtomicInteger instances.

    • AtomicInteger ์ธ์Šคํ„ด์Šค๊ฐ€ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” value๊ฐ’์˜ ์ฃผ์†Œ์ธ๋“ฏ.

  • compareAndSwapInt CAS ๊ธฐ๋ฒ•์œผ๋กœ, do-while๋ฌธ์„ ๋Œ๋ฉด์„œ ํ˜„์žฌ ๋ฉ”์ธ ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๊ฐ’์ด var5์™€ ๊ฐ™์œผ๋ฉด var5 + var4(1) ํ•ด์„œ setํ•˜๊ณ  ์•„๋‹ˆ๋ฉด ๊ณ„์† ๋Œ๋“ฏ.

    • ๋Œ๋‹ค๊ฐ€ ์–ด๋Š์ •๋„ ์ง€๋‚˜๋ฉด ํŠ•๊ธฐ๊ฒ ์ง€..?

์ฐธ๊ณ 

  • https://www.digitalocean.com/community/tutorials/atomicinteger-java

  • https://www.javacodemonk.com/what-is-atomicinteger-class-and-how-it-works-internally-1cda6a56

  • https://www.baeldung.com/java-volatile

  • https://www.geeksforgeeks.org/volatile-keyword-in-java/#:~:text=For%20Java%2C%20%E2%80%9Cvolatile%E2%80%9D%20tells,scope%20of%20the%20program%20itself.

Last updated