Synchronized, Volatile - springscomin/be-was GitHub Wiki
Synchronized
μ€μ§ νλμ μ€λ λλ§ ν΄λΉ λΈλμ μ κ·Όν μ μλλ‘ λ³΄μ₯. (λͺ¨λν°, λ½ λ°©μ μ¬μ©)
- Race Conditionμ νΌνκΈ° μν¨
- Block λλ λ©μλμ λΆμΌ μ μμ.
example
// A Class used to send a message
class Sender {
public void send(String msg) {
System.out.println("Sending\t" + msg);
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}
class ThreadedSend extends Thread {
private String msg;
Sender sender;
ThreadedSend(String m, Sender obj) {
msg = m;
sender = obj;
}
public void run() {
// μ€νκ²°κ³Ό μμΈ‘ν΄λ³΄κΈ°
withSynchronized();
// withOutSynchronized();
}
private void withSynchronized() {
synchronized (sender) {
sender.send(msg);
}
}
private void withOutSynchronized() {
sender.send(msg);
}
}
// Driver class
class SyncDemo {
public static void main(String args[]) {
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);
S1.start();
S2.start();
try {
S1.join();
S2.join();
} catch (Exception e) {
System.out.println("Interrupted");
}
}
}
Reference
- https://medium.com/@basecs101/synchronization-in-java-all-you-need-to-know-latest-6f86185ddf3
- https://www.geeksforgeeks.org/synchronization-in-java/
Volatile
the volatile keyword is essentially lock-free and hence the most lightweight means of providing thread safety.
λ©ν° μ€λ λμμ λμμ μ κ·Όν μ μλ λ°μ΄ν°μ κ²½μ° μΊμλ‘ μΈν΄ λ°μ΄ν° λΆμΌμΉ λ¬Έμ κ° λ°μν μ μλ€.(μΊμ μ΄ν λ€λ₯Έ μ€λ λμμ κ°μ λ³κ²½ νμ λ λ°μ΄ν° λΆμΌμΉ λ°μ)
volatile νλλ μ€ν μ€μΈ CPU μ½μ΄ μΊμμ μΊμνμ§ μκ³ , λͺ¨λ μ½κΈ° μ°κΈ° μμ μ λ©μΈ λ©λͺ¨λ¦¬μ μ§μ μννλ€.
β volatile fieldμ μ κ·Όνλ λͺ¨λ μ€λ λλ λμΌν κ°μ μ»μ μ μλ€.
Reference
Cache Coherence
곡μ λ©λͺ¨λ¦¬λ₯Ό μ¬μ©νμ§λ§ νλ‘μΈμ€λ§λ€ λ€λ₯Έ μΊμ 곡κ°μ κ°λ λ©ν° νλ‘μΈμ μμ€ν μμ, νλμ 곡μ λ°μ΄ν°μ λν λ§μ 볡μ λ³Έμ΄ μκΈΈ μ μλ€.
λ§μ½ λ°μ΄ν°κ° λ°λλ€λ©΄, 볡μ λ³Έλ€λ λ°μ΄ν°μ λ³νλ₯Ό λ°μν΄μΌ νλ€.
β Cache Coherenceλ 곡μ λ°μ΄ν°μ λ³νκ° λ°λ‘ μ νλ μ μλλ‘ ν΄μΌνλ€λ μμΉμ μλ―Ένλ€.