Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Synchronized Methods in Java

Tech Apr 19 46

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

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...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

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