Synchronized Methods in Java
A synchronized method locks the entire method body for thread safety. The syntax is:
modifier synchronized returnType methodName(parameters) {
// method body
}
The lock object is implicitly determined:
- For instance methods, the lock is the current object (
this). - For static methods, the lock is the class object (
ClassName.class).
Example: Cinema Ticket Sales
Simluate selling 100 tickets through three windows using a synchronized method.
class TicketCounter implements Runnable {
private int ticketSold = 0; // Tracks tickets sold (0 to 99 initially)
@Override
public void run() {
while (processSale()) {
// Continue until all tickets are sold
}
}
private synchronized boolean processSale() {
if (ticketSold == 100) {
return false;
}
try {
Thread.sleep(10); // Simulate processing time
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
ticketSold++;
System.out.println(Thread.currentThread().getName() + " sold ticket #" + ticketSold);
return true;
}
}
Execution setup:
public class Main {
public static void main(String[] args) {
TicketCounter counter = new TicketCounter();
Thread window1 = new Thread(counter, "SalesPoint-A");
Thread window2 = new Thread(counter, "SalesPoint-B");
Thread window3 = new Thread(counter, "SalesPoint-C");
window1.start();
window2.start();
window3.start();
}
}
StringBuffer and Thread Safety
StringBuffer provides a thread-safe alternative to StringBuilder. All public methods in StringBuffer are declared with the synchronized keyword, ensuring that multiple threads can operate on a string buffer without corrupting its state. In contrast, StringBuilder offers better performance in single-threaded environments by omitting synchronization.
Choose StringBuffer when thread safety is required; otherwise, perfer StringBuilder for improved performance.