Baspro
Baspro

Reputation: 35

How to chose whether to synchronize an object or a method

I found this synchronization example on the Internet and I don't really understand what the difference is between synchronizing the object and the methods in this particular example. Here the synchronization is on the object sender; would it be possible to synchronize the method send and obtain the same result?

// A Java program to demonstrate working of 
// synchronized. 
import java.io.*; 
import java.util.*; 

// A Class used to send a message 
class Sender 
{ 
    public void send(String msg) 
    { 
        System.out.println("Sending\t"  + msg ); 
        try
        { 
            Thread.sleep(1000); 
        } 
        catch (Exception e) 
        { 
            System.out.println("Thread  interrupted."); 
        } 
        System.out.println("\n" + msg + "Sent"); 
    } 
} 

// Class for send a message using Threads 
class ThreadedSend extends Thread 
{ 
    private String msg; 
    private Thread t; 
    Sender  sender; 

    // Recieves a message object and a string 
    // message to be sent 
    ThreadedSend(String m,  Sender obj) 
    { 
        msg = m; 
        sender = obj; 
    } 

    public void run() 
    { 
        // Only one thread can send a message 
        // at a time. 
        synchronized(sender) 
        { 
            // synchronizing the snd object 
            sender.send(msg); 
        } 
    } 
} 

// Driver class 
class SyncDemo 
{ 
    public static void main(String args[]) 
    { 
        Sender snd = new Sender(); 
        ThreadedSend S1 = 
            new ThreadedSend( " Hi " , snd ); 
        ThreadedSend S2 = 
            new ThreadedSend( " Bye " , snd ); 

        // Start two threads of ThreadedSend type 
        S1.start(); 
        S2.start(); 

        // wait for threads to end 
        try
        { 
            S1.join(); 
            S2.join(); 
        } 
        catch(Exception e) 
        { 
             System.out.println("Interrupted"); 
        } 
    } 
} 

Upvotes: 1

Views: 69

Answers (1)

rghome
rghome

Reputation: 8819

In your example, there is not really any difference between synchronizing on the object and declaring the send method as synchronized.

But in general the advantages of synchronizing on the object are:

  1. The caller can chose whether to synchronize or not.
  2. The caller can place additional code in the synchronized block and not just the call to the send method. (For example if you want to synchronize calls to different objects).

The advantages of synchronizing on the method are:

  1. Synchronization is automatic and determined by the called class. The caller doesn't need to know about it.
  2. You can have synchronized and non-synchonized methods as required.

Upvotes: 2

Related Questions