1. ์ฆ์ ์ด๊ธฐํ
public class IdGnerator {
private AtomicLong id = new AtomicLong(0);
private static final IdGenerator instance = new IdGenerator();
private IdGenerator() {}
public static IdGenerator getInstance() {
return instance;
}
public long getId() {
return id.incrementAndGet();
}
}
2. ๋ฆ์ ์ด๊ธฐํ
public class IdGnerator {
private AtomicLong id = new AtomicLong(0);
private static IdGenerator instance;
private IdGenerator() {}
public static synchronized IdGenerator getInstance() {
if(instance == null) {
instance = new IdGenerator();
}
return instance;
}
public long getId() {
return id.incrementAndGet();
}
}
- ์๊ฐ์ด ์ค๋ ๊ฑธ๋ฆฌ๋ ์ด๊ธฐํ ์์ ์ด ์ธ์คํด์ค๊ฐ ์ฌ์ฉ๋๊ธฐ ์ง์ ์ ์ด๋ฃจ์ด์ง๋ฉด ์ฑ๋ฅ์ ๋ฌธ์ ๋ฐ์ ๊ฐ๋ฅ
- synchronized ํค์๋๋ฅผ ์ฌ์ฉํ๋๋ฐ, IdGenerator ํด๋์ค์ ์ฌ์ฉ ๋น๋๊ฐ ๋๋ค๋ฉด ์์ฃผ ์ ๊ธ์ด ์ผ์ด๋๊ณ ์ด๋ก ์ธํด ๋ณ๋ชฉ ํ์์ด ๋ฐ์ํ ์ ์์
3. ์ด์ค ์ ๊ธ
- ๋ฆ์ ์ด๊ธฐํ ๋ฐฉ์ + ๋ฎ์ ๋์์ฑ์ ํด๊ฒฐ
public class IdGenerator {
private AtomicLong id = new AtomicLong(0);
private static IdGenerator instance;
private IdGenerator() {}
public static IdGenerator getInstance() {
if(instance == null) {
synchronized(IdGenerator.class) {
if(instance == null) {
instance = new IdGenerator();
}
}
}
return instance;
}
public long getId() {
return id.incrementAndGet();
}
}
- CPU ๋ช ๋ น์ด ์ฌ์ ๋ ฌ๋๋ฉด
IdGenerator ํด๋์ค์ ๊ฐ์ฒด๊ฐ new ์์ฝ์ด๋ฅผ ํตํด instance ๋ฉค๋ฒ ๋ณ์๊ฐ ์ง์ ๋ ํ,
์ด๊ธฐํ๊ฐ ์ด๋ฃจ์ด์ง๊ธฐ ์ ์ ๋ค๋ฅธ ์ค๋ ๋์์ ์ด ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๋ ค๊ณ ํ ์ ์์
- volatile ํค์๋๋ฅผ ์ธ์คํด์ค ๋ฉค๋ฒ ๋ณ์์ ์ถ๊ฐํ์ฌ ๋ช ๋ น์ด ์ฌ์ ๋ ฌ ๋ฐฉ์ง
4. ํ๋์ ์ํ ์ด๊ธฐํ
- ์ง์ฐ ๋ก๋ฉ + ์ค๋ ๋ ์์ ์ฑ
- ์ ์ ๋ด๋ถ ํด๋์ค ํ์ฉ
public class IdGenerator {
private AtomicLong id = new AtomicLong(0);
private IdGenerator() {}
private static class SingletonHolder {
private static final IdGenerator instance = new IdGenerator();
}
public static IdGenerator getInstance() {
return SingletonHolder.instance;
}
public long getId() {
return id.incrementAndGet();
}
}
IdGenerator ์ ์ฌ ์์ ์๋ SingetonHolder๋ ์ ์ฌ๋์ง ์์ง๋ง,
getInstance()๊ฐ ์ฒ์์ผ๋ก ํธ์ถ๋ ๋ ์ ์ฌ๋๊ณ ์์ฑ๋๋ค
๋ฐ๋ผ์ JVM์ ์ํด ์ธ์คํด์ค์ ์ ์ผ์ฑ๊ณผ ์์ฑ ํ๋ก์ธ์ค์ ์ค๋ ๋ ์์ ์ฑ์ด ๋ณด์ฅ๋๋ค
5. ์ด๊ฑฐ
- enum ํ์ฉํ์ฌ ์ธ์คํด์ค ์์ฑ์ ์ค๋ ๋ ์์ ์ฑ๊ณผ ์ ์ผ์ฑ์ ๋ณด์ฅํจ
public enum IdGenerator {
INSTANCE;
private AtomicLong id = new AtomicLong(0);
public long getId() {
return id.incrementAndGet();
}
}
์ฑ๊ธํค ํจํด์
ํด๋์ค ๊ฐ์ ์์กด์ฑ์ ๊ฐ์ถ๋ค
์ฝ๋์ ํ์ฅ์ฑ/ํ ์คํธ์ ์ํฅ์ ๋ฏธ์น๋ค
๋งค๊ฐ๋ณ์๊ฐ ์๋ ์์ฑ์๋ฅผ ์ง์ํ์ง ์๋๋ค
๋์ ? ํฉํฐ๋ฆฌ ํจํด, DI ์ปจํ ์ด
| ๋น๋ํจํด ์ง์ ๊ตฌํํด๋ณด๊ธฐ (0) | 2024.11.05 |
|---|---|
| [๋์์ธํจํด] ํฉํฐ๋ฆฌํจํด (0) | 2024.05.05 |
| [๋์์ธํจํด์ ์๋ฆ๋ค์] 3์ฅ. ์ค๊ณ ์์น : ๋จ์ผ์ฑ ์์์น, ๊ฐ๋ฐฉํ์ ์์น (0) | 2024.04.20 |
| ์ด๋ํฐ ํจํด (0) | 2024.03.05 |