The synchronized keyword in Java is used to ensure that only one thread can access a shared resource or critical section of code at a time. It helps prevent race conditions and maintains data consistency in multithreaded applications.
Key Points: • synchronized provides thread-safe access to shared resources. • It prevents multiple threads from executing a critical section simultaneously. • It can be applied to methods or code blocks. • Every Java object has an intrinsic lock (monitor) that synchronized uses for locking. • Excessive synchronization can impact performance because threads may have to wait for locks.
Example: In a banking application, if multiple threads try to withdraw money from the same account simultaneously, synchronized ensures that only one thread updates the account balance at a time.
Code Example:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}Interview Tip: A concise interview answer is:
"The synchronized keyword is used to make code thread-safe by allowing only one thread to access a shared resource at a time. It helps prevent race conditions and ensures data consistency in multithreaded applications."