-1

I wonder what the synchronized key word do in below code, one is at send() method, another is at receive() method.

In which race condition scenario/scenarios the synchronized keyword want to prevent?

Thank you very much!

public class Data {
    private String packet;

    // True if receiver should wait
    // False if sender should wait
    private boolean transfer = true;

    public synchronized void send(String packet) {
        while (!transfer) {
            try { 
                wait();
            } catch (InterruptedException e)  {
                Thread.currentThread().interrupt(); 
                Log.error("Thread interrupted", e); 
            }
        }
        transfer = false;

        this.packet = packet;
        notifyAll();
    }

    public synchronized String receive() {
        while (transfer) {
            try {
                wait();
            } catch (InterruptedException e)  {
                Thread.currentThread().interrupt(); 
                Log.error("Thread interrupted", e); 
            }
        }
        transfer = true;

        notifyAll();
        return packet;
    }
}
Ajay Sivan
  • 2,807
  • 2
  • 32
  • 57
Nan Wu
  • 7
  • 1

1 Answers1

0

The synchronized keyword in Java ensures that only one thread can be in a method at a single time. It's equivalent to placing a semaphore flag around a method, if you're familiar with other concurrency patterns.

Read more about it, with some helpful examples, here: https://www.baeldung.com/java-synchronized

Malcolm Crum
  • 4,345
  • 4
  • 30
  • 49
  • Re, "...in a method..." The methods are not what's important. The purpose of a mutex (e.g., a `synchronized` block) is to prevent other threads from seeing shared _data_ in an inconsistent state while one thread is in the process of updating it. Sometimes there's only one method that touches the shared data, and protecting the method then is equivalent to protecting the data. But in other cases, there could be any number of different methods that all access the same data, and they _all_ must be `synchronized` on the same object to achieve thread safety. – Solomon Slow Apr 15 '19 at 13:56