Site icon DataFlair

What is Java Synchronized Method | Java Synchronized Block

Free Java courses with 37 real-time projects - Learn Java

1. Objective

In our last Java Tutorial, we studied about Deadlock in Java. Here, we are going to learn What is Synchronization in Java. Moreover, we will discuss the Java Synchronized method and Java Synchronized block.

So, let’s study Synchronized Methods & Blocks in Java.

2. What is Java Synchronized?

Do you know What is Decision Making in Java?

The syntax of Synchronized in Java:

synchronized(sync_object)
{
}

Java synchronization implements inside with a concept called as monitors. This monitor own by only one thread for a given time.

3. Example of Synchronized in Java

import java.io.*;
import java.util.*;
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 ThreadedSend extends Thread
{
private String msg;
private Thread t;
Sender sender;
ThreadedSend(String m, Sender obj)
{
msg = m;
sender = obj;
}
public void run()
{
synchronized(sender)
{
// synchronizing the snd object
sender.send(msg);
}
}
}
class SyncDemo
{
public static void main(String args[])
{
Sender snd = new Sender();
ThreadedSend S1 =
new ThreadedSend( " Hi " , snd );
ThreadedSend S2 =
new ThreadedSend( " Bye " , snd );
S1.start();
S2.start();
try
{
S1.join();
S2.join();
catch(Exception e)
{
System.out.println("Interrupted");
}
}
}

Do you know about Polymorphism in Java 

In the example stated above we choose to synchronize the sender object inside the run() method of the ThreadedSend class.

class Sender
{
public synchronized 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");
}
}

Synchronizing the whole a method is not always necessary. Sometimes parts of a method synchronized in Java.

class Sender
{
public void send(String msg)
{
synchronized(this)
{
System.out.println("Sending\t" + msg );
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}
}

Follow this link to know about Hierarchical Data Structure in Java

So, this was all about synchronization in Java Tutorial. Hope you like our explanation.

4. Conclusion

Hence, we studied synchronization in java programming Langauge. In addition, we saw the Java synchronized method and blocks in detail. In our next tutorial, we will see Semaphore in Java. Furthermore, if you have any query, feel free to ask in the comment section. Surely we will get back to you.

Keep Learning and Keep Visiting!

Related Topic- Java Garbage Collection Algorithm 

For reference 

Exit mobile version