Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Thread Synchronization in Java

Tech May 14 1

Java provides synchronization mechanisms to prevent resource access conflicts in multi-threaded applications.

  1. Thread Safety Issues

Real-world applications like banking systems or ticket booking systems often encounter problems when multiple threads access shared resources simultaneously. Consider a ticket booking system where two threads check remaining tickets at the same time when only one ticket remains. Both threads might proceed to sell the ticket, resulting in negative counts.

class TicketSystem implements Runnable {
    int availableTickets = 10;
    
    public void run() {
        while (true) {
            if (availableTickets > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Selling ticket " + availableTickets--);
            }
        }
    }
    
    public static void main(String[] args) {
        TicketSystem system = new TicketSystem();
        new Thread(system).start();
        new Thread(system).start();
        new Thread(system).start();
    }
}

This implementation demonstrates the race condition problem where multiple threads can sell the same ticket.

  1. Synchronization Mechanisms

Java offers two primary apporaches to handle thread synchronization:

(1) Synchronized Blocks

synchronized(lockObject) {
    // critical section
}

Example implementation:

class SafeTicketSystem implements Runnable {
    int availableTickets = 10;
    Object lock = new Object();
    
    public void run() {
        while (true) {
            synchronized (lock) {
                if (availableTickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Selling ticket " + availableTickets--);
                }
            }
        }
    }
}

(2) Synchronized Methods

public synchronized void processTicket() {
    // critical section
}

When a thread enters a synchronized method, other threads must wait until the current thread completes execution of the method.

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.