Web/Spring

[๋™์‹œ์„ฑ] Java Concurrency Control(asynchronous, synchronized)

Aaron 2024. 8. 16. 20:56
๋ฐ˜์‘ํ˜•

๐ŸŽฏ Java Concurrency Control

Race Condition

๊ฒฝ์Ÿ์ƒํƒœ๋Š” ๋‘ ๊ฐœ ์ด์ƒ์˜ ์Šค๋ ˆ๋“œ๊ฐ€ ๊ณต์œ  ๋ฐ์ดํ„ฐ์— ์•ก์„ธ์Šค ํ•  ์ˆ˜ ์žˆ๊ณ , ๋™์‹œ์— ๋ณ€๊ฒฝ์„ ํ•˜๋ ค๊ณ  ํ•  ๋•Œ ๋ฐœ์ƒํ•˜๋Š” ๋ฌธ์ œ

  • Race Condition ์œผ๋กœ ๋™์‹œ์— ๋“ค์–ด์˜ค๋Š” ์š”์ฒญ๋“ค์ด ๊ฐฑ์‹  ์ „ ๊ฐ’์„ ์ฝ๊ณ , ์ˆ˜์ •ํ•˜๋ฉด์„œ
  • ์‹ค์ œ ๊ฐฑ์‹ ์ด ๋ˆ„๋ฝ๋˜๋Š” ํ˜„์ƒ์ด ๋ฐœ์ƒ

Series

Java Concurrency Control

Database Concurrency Control

Redis Concurrency Control

Kafka Concurrency Control

Compare Concurrency Control

๐Ÿน Java Asynchronous

๋™์‹œ์— ๋“ค์–ด์˜ค๋Š” ์š”์ฒญ๋“ค์ด ๊ฐฑ์‹  ์ „ ๊ฐ’์„ ์ฝ๊ณ , ์ˆ˜์ •ํ•˜๋ฉด์„œ ์‹ค์ œ ๊ฐฑ์‹ ์ด ๋ˆ„๋ฝ

before: 100, after: 99 // ๊ฐฑ์‹  ์ „ ๊ฐ’์„ ์กฐํšŒ
before: 100, after: 99
before: 100, after: 99
...
before: 95, after: 94
before: 98, after: 97
before: 100, after: 99
before: 88, after: 87
before: 92, after: 91
before: 99, after: 98

.

java asynchronous example

.

๐Ÿ› ๏ธ ์„ฑ๋Šฅ ํ…Œ์ŠคํŠธ.

  • ํ•œ์ • ์ˆ˜๋Ÿ‰: 50,000
  • User: 296
  • Processes: 8
  • Threads: 37
  • Duration: 3 min

๊ฒฐ๊ณผ๋ฅผ ๋ณด๋ฉด ํ•œ์ • ์ˆ˜๋Ÿ‰์€ 50,000 ์œผ๋กœ ์ œํ•œํ–ˆ์ง€๋งŒ 121,933 ๊ฑด์ด ์ดˆ๊ณผ๋œ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

๋™์‹œ์„ฑ ์ฒ˜๋ฆฌ๊ฐ€ ๋˜๊ณ  ์žˆ์ง€ ์•Š๋‹ค๋ณด๋‹ˆ ๋ชจ๋“  ์š”์ฒญ์ด ์„ฑ๊ณตํ•˜๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

Result

๐Ÿน Java Synchronized

synchronized ๋ฅผ ๋ฉ”์„œ๋“œ ์„ ์–ธ๋ถ€์— ๋ถ™์—ฌ์ฃผ๋ฉด ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋Š” ํ•œ ๊ฐœ์˜ ์Šค๋ ˆ๋“œ๋งŒ ์ ‘๊ทผ ๊ฐ€๋Šฅ

ํ•œ ๊ฐœ์˜ ์Šค๋ ˆ๋“œ๋งŒ ์ ‘๊ทผ ๊ฐ€๋Šฅํ•˜๋„๋ก ์ œํ•œํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ํฐ ๋ฌธ์ œ๊ฐ€ ์กด์žฌ

  • (1) @Transactional ์‚ฌ์šฉ ์‹œ ํ”„๋ก์‹œ ๋ฐฉ์‹์˜ AOP๊ฐ€ ์ ์šฉ๋˜์–ด ํŠธ๋žœ์žญ์…˜ ์ข…๋ฃŒ ์ „์— ๋‹ค๋ฅธ ์Šค๋ ˆ๋“œ๊ฐ€ ๊ฐฑ์‹ ๋œ ์ „ ๊ฐ’์„ ์ฝ๊ฒŒ ๋˜๋ฉด ๊ฒฐ๊ตญ ์ด์ „๊ณผ ๋™์ผํ•œ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒ
  • (2) ํ•˜๋‚˜์˜ ํ”„๋กœ์„ธ์Šค ์•ˆ์—์„œ๋งŒ ๋ณด์žฅ โ†’ ์„œ๋ฒ„๊ฐ€ 2๋Œ€ ์ด์ƒ์ผ ๊ฒฝ์šฐ ๊ฒฐ๊ตญ ์—ฌ๋Ÿฌ ์Šค๋ ˆ๋“œ์—์„œ ๋™์‹œ์— ๋ฐ์ดํ„ฐ์— ์ ‘๊ทผ

.

java synchronous example

.

๐Ÿ› ๏ธ ์„ฑ๋Šฅ ํ…Œ์ŠคํŠธ.

  • ํ•œ์ • ์ˆ˜๋Ÿ‰: 50,000
  • User: 296
  • Processes: 8
  • Threads: 37
  • Duration: 3 min

๊ฒฐ๊ณผ๋ฅผ ๋ณด๋ฉด ํ•œ์ • ์ˆ˜๋Ÿ‰์€ 50,000 ์œผ๋กœ ์ œํ•œํ–ˆ์ง€๋งŒ 49,971 ๊ฑด์ด ์ดˆ๊ณผ๋œ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

๋‹ค์ˆ˜์˜ ํ”„๋กœ์„ธ์Šค์—์„œ ์š”์ฒญ์ด ์˜ฌ ๊ฒฝ์šฐ ๊ฒฐ๊ตญ ์—ฌ๋Ÿฌ ์Šค๋ ˆ๋“œ์—์„œ ๋™์‹œ์— ๋ฐ์ดํ„ฐ์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

02:48 ์ดํ›„์—๋Š” ๋ชจ๋“  ์ˆ˜๋Ÿ‰์ด 0์œผ๋กœ ์กฐํšŒ๋˜์–ด, ์žฌ๊ณ  ๋ถ€์กฑ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜๊ฒŒ ๋œ๋‹ค.

Result

๋ฐ˜์‘ํ˜•