Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Sign in Get started

WRIT E FOR US CODING INT ERVIEW COURS E →

You have 2 free stories left this month. Sign up and get an extra one for free.

How to use Synchronization in Java


A complete guide to Synchronize your Java code
Manusha Chethiyawardhana Follow
May 25 · 4 min read

Photo by Gabriel Gusmao on Unsplash

Many Java programmers work with multi-threaded code. It’s very


important to know about synchronization when working with multiple
threads. Synchronization is used to make your code thread-safe. Even
the Java Collections Framework has a set of synchronized methods so
that we can work with them in multi-threaded environments. Good
knowledge of multi-threading and synchronization could make your life
as a programmer a lot easier.

In this article, you will learn why we need Java synchronization, how to
write synchronized code, and more important points about
synchronization.

. . .

Why use Synchronization?


If your code is running in a multi-threaded environment, You need to
synchronize the objects that are shared across multiple threads. If not,
two types of errors could occur.

1. Thread Interference Error

2. Memory Consistency Error

Thread interference in java is a condition that occurs when more than


one thread, running simultaneously, has access to the same piece of data.
When threads perform different operations on the same data, the
operations may overlap and create inconsistent data in the memory.
When that happens, the data might get lost, corrupted, or show
unexpected behavior.

In multithreading, there may be possibilities that changes made by one


thread may not be visible to the other threads and that they all have
inconsistent views of the same shared data. This is known as the memory
consistency error.

So, we’re using synchronization in our code to avoid getting headaches


from these errors. You do not need to use synchronization if shared
objects are immutable or if all threads only perform read-only
operations. Now let’s see how to synchronize our Java code.

Method Synchronization
You can declare a synchronized method in Java by using the
synchronized keyword. When a thread invokes a synchronized method, it
automatically locks an object when it has shared data and releases it
when the thread completes its task. So, if one thread runs the
synchronized method, all other threads that invoke the synchronized
method on the same object will have to wait until the first thread is
finished. Let’s see an example.

1 class Apple {
2 synchronized public void getApple() {
3 for (int i = 0; i < 3; i++) {
4 System.out.println(i);
5 try {
6 Thread.sleep(400);
7 }
8 catch (Exception e) {
9 System.out.println(e);
10 }
11 }
12 }
13 }
14
15 class Tree extends Thread {
16
17 Apple apple;
18
19 Tree (Apple apple) {
20 this.apple = apple;
21 }
22
23 @Override
24 public void run() {
25 apple.getApple();
26 }
27 }
28
29 public class SyncEx1 {
30 public static void main(String[] args) {
31
32 Apple obj = new Apple(); //Object of Apple class that is shared amoung threads
33
34 Tree tree1 = new Tree(obj);
35 Tree tree2 = new Tree(obj);
36
37 tree1.start();
38 tree2.start();
39 }
40 }

SyncEx1.java hosted with ❤ by GitHub view raw

The getApple() method is synchronized in the example, allowing only


one thread to access that method at a time. Because of this, the value of
the variable i will not be inconsistent. But what if we just want to
synchronize a piece of code and not the whole method. That’s when
we’re going to need block synchronization.

Block Synchronization
Suppose you have 50 lines of code in your method, but you just want to
synchronize 5 lines. The synchronized block allows you to synchronize
any specific part of the method. It tells the JVM to allow only one thread
to access the specified piece of code at a time.

The synchronizedList() method of java.util.Collections class is used to


return a synchronized list backed by the specified list. So, whenever
the Iterator is used to iterate through a synchronized list, the block of
code using the Iterator needs to be synchronized. Let’s look at the
example code for this.

1 import java.util.*;
2 public class SyncEx2{
3
4 public static void main(String []args){
5 try{
6 List<String> al = new ArrayList<>();
7 List movieList = Collections.synchronizedList(al);
8 movieList.add("StarWars");
9 movieList.add("Avengers");
10 movieList.add("Inception");
11
12 synchronized(movieList) { // Synchronized block
13 Iterator i = movieList.iterator();
14 while (i.hasNext())
15 System.out.println(i.next()); // Print Synchronized movie list
16 }
17
18 } catch (IllegalArgumentException e) {
19 System.out.println("Exception thrown : " + e);
20 }
21 }
22 }

SyncEx2.java hosted with ❤ by GitHub view raw

. . .

Important Notes on Synchronization


If you synchronize a static method, the lock will be on the class, not
on the object. So no matter how many instances it may have, only one
thread can run within a class of static synchronized methods.

There are 3 inter-thread communication methods that can be used


inside synchronized methods or blocks. Those are wait() , notify() ,

and notifyAll() .

You can use the wait() method to set the current thread to release
the lock and wait until another thread invokes the notify() method
or notifyAll() method for this object, or until the specified time has
elapsed.

The notify() method will choose and wakeup a single thread that is
waiting on this object, and the notifyAll() method will wake up all
the threads that are waiting on this object’s monitor.

There are many limitations in synchronization, it does not allow


concurrent access, it could cause deadlocks, and synchronized
methods are very slow in execution.

Java has introduced the java.util.concurrent package in Java 5, and


it can be used as a solution to these problems. The package provides a
set of classes that make it easier to develop multi-threaded Java
applications.

. . .

Although there are limitations in Java synchronization, it is still useful


when working with multi-threaded environments. I hope you learned
something new from this article and hope to bring you more Java
knowledge in the future.

Thank you so much for reading and happy coding!

Programming Java Technology Coding Software Development

431 claps

WRIT T EN BY

Manusha Chethiyawardhana Follow

manushacheti@gmail.com | Undergraduate at UOM IT


faculty and Taekwondo player

Level Up Coding Follow

Coding tutorials and news. The developer homepage


gitconnected.com

Write the rst response

More From Medium

Top 5 Reasons How To Become A True To My Programmer Self 5 JavaScript T ips I


Javascript Developers Keyboard Warrior (And 20 Years Ago: Do T hese Learned From Vue
Prefer Deno Over Node Stop Using Your Mouse) 4 T hings More Source Code
Dan Halperin in Level Up keypressingmonkey in Level Alvin Lee in Level Up Coding bit sh in Level Up Coding
Coding Up Coding

How to use Generics in 7 T hings to Build When React Antipatterns to AWS CDK for Beginners
Java You Feel Bored as a Avoid Rani Lian in Level Up Coding
Manusha Chethiyawardhana in Programmer John Au-Yeung in Level Up
Level Up Coding Daan in Level Up Coding Coding

Discover Medium Make Medium yours Become a member


Welcome to a place where words matter. On Medium, smart Follow all the topics you care about, and we’ll deliver the Get unlimited access to the best stories on Medium — and
voices and original ideas take center stage - with no ads in best stories for you to your homepage and inbox. Explore support writers while you’re at it. Just $5/month. Upgrade
sight. Watch

About Help Legal

You might also like