Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Synchronized Methods in Java

Tech 1

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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.