2023. 2. 28. 15:36γJAVA/Effective JAVA
item17. λ³κ²½ κ°λ₯μ±μ μ΅μν νλΌ.
" p.113 java.util.concurrent ν¨ν€μ§μ CountDownLatch ν΄λμ€κ° μ΄μμ μμΉμ μ λ°©μ¦νλ€."
java.util.concurrent ν¨ν€μ§
: λ³ν(Concurrency) νλ‘κ·Έλλ°μ μ μ©νκ² μ¬μ©ν μ μλ μ νΈλ¦¬ν° λ¬Άμ
- λ³ν(Concurrency)μ λ³λ ¬(Parallelism)μ μ°¨μ΄
λ³νμ μ¬λ¬ μμ μ λ²κ°μ κ°λ©° μ€νν΄ λ§μΉ λμμ μ¬λ¬ μμ μ λμμ μ²λ¦¬νλ― λ³΄μ΄μ§λ§, μ€μ λ‘λ ν λ²μ μ€μ§ ν μμ λ§μ μ€ννλ€. (cpuκ° νκ°μ¬λ κ°λ₯)
λ³λ ¬μ μ¬λ¬ μμ μ μ€μ λ‘ λμμ μ²λ¦¬νλ κ²μΌλ‘ cpuκ° μ¬λ¬κ° μμ΄μΌ κ°λ₯νλ€.
μλ°μ concurrent ν¨ν€μ§μμλ λ³ν μ ν리μΌμ΄μ μ μ μ©ν λ€μν ν΄μ μ 곡νλ€.
-> BlockingQueue, Callable, ConcurrentMap, Executor, ExecutorService, Future. ...
CountDownLatch
: λ€λ₯Έ μ¬λ¬ μ€λ λλ‘ μ€ννλ μ¬λ¬ μ€νΌλ μ΄μ μ΄ λ§μΉ λκΉμ§ κΈ°λ€λ¦΄ λ μ¬μ©ν μ μλ μ νΈλ¦¬ν°
CountDownLatchλ μ€λ λ nκ°λ₯Ό μ€ννκ³ μΌμ κ°μμ μ€λ λκ° λͺ¨λ λλ λ κΉμ§ κΈ°λ€λ €μΌλ§ λ€μμΌλ‘ μ§νν μμκ±°λ λ€λ₯Έ μ€λ λ€λ₯Ό μ€νμν¬ μ μλ κ²½μ°μ μ¬μ©νλ€.
public class ConcurrentExample
{
public static void main(String[] args) throws InterruptedException
{
int N = 10;
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(N);
for (int i = 0; i< N; i++) // create and start threads
{
new Thread(new Worker(startSignal, doneSignal)).start();
}
ready(); // don't let run yet
startSignal.countDown(); // let all threads proceed
doneSignal.await(); // wait for all to finish
done();
}
private static void ready()
{
System.out.println("ready~~~");
}
private static void done()
{
System.out.println("done~~~");
}
private static class Worker implements Runnable
{
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
public Worker(CountDownLatch startSignal, CountDownLatch doneSignal)
{
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
@Override
public void run()
{
try
{
doWork();
doneSignal.countDown();
startSignal.await();
}
catch (InterruptedException e) {
}
}
void doWork()
{
System.out.println("working thread : " + Thread.currentThread().getName());
}
}
}
CountDownLatchλ μ΄κΈ°νν λ μ μκ° countλ₯Ό λ£μ΄μ£Όκ³ μ€λ λλ λ§μ§λ§μ countDown() λ©μ λλ₯Ό λΆλ¬μ€λ€.
κ·Έλ¬λ©΄ μ΄κΈ°νν λ λ£μ΄μ€ μ μκ°μ΄ νλ λ΄λ €κ°κ³ , κ° μ€λ λλ λ§μ§λ§μ μμ μ΄ μ€νμλ£νμμ countDown λ©μλλ‘ μλ €μ€λ€.
κ·Έλ¦¬κ³ μ΄ μ€λ λλ€μ΄ λλκΈ°λ₯Ό κΈ°λ€λ¦¬λ μͺ½ μ μ₯μμλ await() λ©μλλ₯Ό λΆλ¬μ€λ€. κ·Έλ¬λ©΄ νμ¬ λ©μλκ° μ€νμ€μΈ λ©μΈμ€λ λλ λμ΄μ μ§ννμ§ μκ³ countDownLatchμ countκ° 0μ΄ λ λκΉμ§ κΈ°λ€λ¦°λ€.
int N = 10;
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(N);
-> μ΄κΈ°ν ν λ μ«μλ₯Ό μ λ ₯νκ³ ,
startSignal.countDown(); // let all threads proceed
doneSignal.await(); // wait for all to finish
await() λ©μλλ₯Ό μ¬μ©ν΄μ μ«μκ° 0μ΄ λ λκΉμ§ κΈ°λ€λ¦°λ€. κ·Έλ¦¬κ³ μ«μλ₯Ό μ λλ countDown() λ©μλλ₯Ό μ¬μ©νλ€.
countDownLatchλ μμ λλ μ’ λ£ μ νΈλ‘ μ¬μ©ν μ μμΌλ©°, μ¬μ¬μ©ν μ μλ μΈμ€ν΄μ€κ° μλκΈ° λλ¬Έμ μ«μλ₯Ό 리μ ν΄μ μ¬μ¬μ©νλ €λ©΄ CyclicBarrierλ₯Ό μ¬μ©ν΄μΌ νλ€.