Inter-thread communication and Deadlock in Java

Last updated on Dec 25 2022
Prabhas Ramanathan

Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class:
• wait()
• notify()
• notifyAll()

Table of Contents

1) wait() method

Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object’s monitor, so it must be called from the synchronized method only otherwise it will throw exception.

Method Description
public final void wait()throws InterruptedException waits until object is notified.
public final void wait(long timeout)throws InterruptedException waits for the specified amount of time.

2) notify() method

Wakes up a single thread that is waiting on this object’s monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax:
public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object’s monitor. Syntax:
public final void notifyAll()

Understanding the process of inter-thread communication

java 68

The point to point explanation of the above diagram is as follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.

Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?

It is because they are related to lock and object has a lock.

Difference between wait and sleep?

Let’s see the important differences between wait and sleep methods.

wait() sleep()
wait() method releases the lock sleep() method doesn’t release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is completed.

Example of inter thread communication in java

Let’s see the simple example of inter thread communication.

1. class Customer{ 
2. int amount=10000; 
3. 
4. synchronized void withdraw(int amount){ 
5. System.out.println("going to withdraw..."); 
6. 
7. if(this.amount<amount){ 
8. System.out.println("Less balance; waiting for deposit..."); 
9. try{wait();}catch(Exception e){} 
10. } 
11. this.amount-=amount; 
12. System.out.println("withdraw completed..."); 
13. } 
14. 
15. synchronized void deposit(int amount){ 
16. System.out.println("going to deposit..."); 
17. this.amount+=amount; 
18. System.out.println("deposit completed... "); 
19. notify(); 
20. } 
21. } 
22. 
23. class Test{ 
24. public static void main(String args[]){ 
25. final Customer c=new Customer(); 
26. new Thread(){ 
27. public void run(){c.withdraw(15000);} 
28. }.start(); 
29. new Thread(){ 
30. public void run(){c.deposit(10000);} 
31. }.start(); 
32. 
33. }}

Output: going to withdraw…
Less balance; waiting for deposit…
going to deposit…
deposit completed…
withdraw completed

Deadlock in java

Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.

java 69

Example of Deadlock in java

1. public class TestDeadlockExample1 { 
2. public static void main(String[] args) { 
3. final String resource1 = "ratan jaiswal"; 
4. final String resource2 = "vimal jaiswal"; 
5. // t1 tries to lock resource1 then resource2 
6. Thread t1 = new Thread() { 
7. public void run() { 
8. synchronized (resource1) { 
9. System.out.println("Thread 1: locked resource 1"); 
10. 
11. try { Thread.sleep(100);} catch (Exception e) {} 
12. 
13. synchronized (resource2) { 
14. System.out.println("Thread 1: locked resource 2"); 
15. } 
16. } 
17. } 
18. }; 
19. 
20. // t2 tries to lock resource2 then resource1 
21. Thread t2 = new Thread() { 
22. public void run() { 
23. synchronized (resource2) { 
24. System.out.println("Thread 2: locked resource 2"); 
25. 
26. try { Thread.sleep(100);} catch (Exception e) {} 
27. 
28. synchronized (resource1) { 
29. System.out.println("Thread 2: locked resource 1"); 
30. } 
31. } 
32. } 
33. }; 
34. 
35. 
36. t1.start(); 
37. t2.start(); 
38. } 
39. } 
40.

Output: Thread 1: locked resource 1
Thread 2: locked resource 2

Interrupting a Thread:

If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn’t interrupt the thread but sets the interrupt flag to true. Let’s first see the methods provided by the Thread class for thread interruption.

The 3 methods provided by the Thread class for interrupting a thread

• public void interrupt()
• public static booleaninterrupted()
• public booleanisInterrupted()

Example of interrupting a thread that stops working

In this example, after interrupting the thread, we are propagating it, so it will stop working. If we don’t want to stop the thread, we can handle it where sleep() or wait() method is invoked. Let’s first see the example where we are propagating the exception.

1. class TestInterruptingThread1 extends Thread{ 
2. public void run(){ 
3. try{ 
4. Thread.sleep(1000); 
5. System.out.println("task"); 
6. }catch(InterruptedException e){ 
7. throw new RuntimeException("Thread interrupted..."+e); 
8. } 
9. 
10. } 
11. 
12. public static void main(String args[]){ 
13. TestInterruptingThread1 t1=new TestInterruptingThread1(); 
14. t1.start(); 
15. try{ 
16. t1.interrupt(); 
17. }catch(Exception e){System.out.println("Exception handled "+e);} 
18. 
19. } 
20. }

 

download this example
Output:Exception in thread-0

java.lang.RuntimeException: Thread interrupted…
java.lang.InterruptedException: sleep interrupted
at A.run(A.java:7)

Example of interrupting a thread that doesn’t stop working

In this example, after interrupting the thread, we handle the exception, so it will break out the sleeping but will not stop working.

1. class TestInterruptingThread2 extends Thread{ 
2. public void run(){ 
3. try{ 
4. Thread.sleep(1000); 
5. System.out.println("task"); 
6. }catch(InterruptedException e){ 
7. System.out.println("Exception handled "+e); 
8. } 
9. System.out.println("thread is running..."); 
10. } 
11. 
12. public static void main(String args[]){ 
13. TestInterruptingThread2 t1=new TestInterruptingThread2(); 
14. t1.start(); 
15. 
16. t1.interrupt(); 
17. 
18. } 
19. }

 

download this example
Output:Exception handled
java.lang.InterruptedException: sleep interrupted
thread is running…

Example of interrupting thread that behaves normally

If thread is not in sleeping or waiting state, calling the interrupt() method sets the interrupted flag to true that can be used to stop the thread by the java programmer later.

1. class TestInterruptingThread3 extends Thread{ 
2. 
3. public void run(){ 
4. for(int i=1;i<=5;i++) 
5. System.out.println(i); 
6. } 
7. 
8. public static void main(String args[]){ 
9. TestInterruptingThread3 t1=new TestInterruptingThread3(); 
10. t1.start(); 
11. 
12. t1.interrupt(); 
13. 
14. } 
15. }

 

Output:1
2
3
4
5

 

What about isInterrupted and interrupted method?

The isInterrupted() method returns the interrupted flag either true or false. The static interrupted() method returns the interrupted flag afterthat it sets the flag to false if it is true.

1. public class TestInterruptingThread4 extends Thread{ 
2. 
3. public void run(){ 
4. for(int i=1;i<=2;i++){ 
5. if(Thread.interrupted()){ 
6. System.out.println("code for interrupted thread"); 
7. } 
8. else{ 
9. System.out.println("code for normal thread"); 
10. } 
11. 
12. }//end of for loop 
13. } 
14. 
15. public static void main(String args[]){ 
16. 
17. TestInterruptingThread4 t1=new TestInterruptingThread4(); 
18. TestInterruptingThread4 t2=new TestInterruptingThread4(); 
19. 
20. t1.start(); 
21. t1.interrupt(); 
22. 
23. t2.start(); 
24. 
25. } 
26. }

 

Output:Code for interrupted thread
code for normal thread
code for normal thread
code for normal thread

So, this brings us to the end of blog. This Tecklearn ‘Inter-thread communication and Deadlock in Java’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

 

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Inter-thread communication and Deadlock in Java"

Leave a Message

Your email address will not be published. Required fields are marked *