Volatile and synchronized

In Java, the volatile and synchronized keywords are used to address issues related to concurrent programming and ensure proper synchronization between threads.

volatile Keyword:

The volatile keyword is used to declare a variable as volatile. When a variable is declared as volatile, it ensures that any thread reading the variable sees the most recent modification made by any other thread.

public class SharedResource {
    private volatile int counter = 0;

    public void increment() {
        counter++;
    }

    public int getCounter() {
        return counter;
    }
}

synchronized Keyword:

The synchronized keyword is used to create mutually exclusive blocks of code, also known as critical sections. When a method or a block of code is marked as synchronized, only one thread can execute that method or block at a time. This helps in preventing race conditions and ensures that shared resources are accessed in a thread-safe manner.

public class SharedResource {
    private int counter = 0;

    public synchronized void increment() {
        counter++;
    }

    public synchronized int getCounter() {
        return counter;
    }
}