Click here to Skip to main content
14,970,019 members
Articles / Programming Languages / Java
Article
Posted 16 Jun 2021

Tagged as

Stats

1.7K views
3 bookmarked

Threading in Java: Object Locks - IV

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
16 Jun 2021CPOL2 min read
This is in continuance with my previous article on "Threading in Java: Object Locks - III"
This series of articles makes an attempt to help readers with the concept of locks in Java. It is assumed that the reader has some prior knowledge of Java and threads creation in Java.

Introduction

Till now in the series of "Threading in Java: Object Locks" articles, we have seen how object locks can synchronize threads created out of object belonging to the same class, e.g., threads t1 and t2 created out of p1 and how object locks can synchronize threads created out of two different objects but belonging to the same class, e.g., threads t1 and t2 created out of processor objects p1 and p2 respectively.

In this article, we will see how object lock can help synchronize threads that are created out of two different objects which belong to totally different classes. To demonstrate this, we will have two different classes, viz., the processor class and the memory class. Take the following program:

Java
locks.java
-----------

class processor implements Runnable{
    Object objLock;
    public processor(Object objLock){
        this.objLock = objLock;
    }
    public void run() {
        executeInstructions(); 
    }
    public void executeInstructions() {
        synchronized(objLock) {
            for (int i = 0 ; i<= 5; i++) {
                System.out.println("i = " + i + " In thread executeInstructions 
                                    of processor class" + Thread.currentThread());
            }
        }   
    }
} 

class memory implements Runnable{
    Object objLock;
    public memory(Object objLock){
        this.objLock = objLock;
    }
    public void run() {
        checkMemory(); 
    }
    public void checkMemory() {
        synchronized(objLock) {
            for (int i = 0 ; i<= 5; i++) {
                System.out.println("i = " + i + " In thread checkMemory 
                                    of memory class" + Thread.currentThread());
            }
        }   
    }
} 

class locks {
    public static void main(String[] args) {
        Object objLock = new Object();
        processor p1 = new processor(objLock);
        memory m1 = new memory(objLock);
        Thread t1 = new Thread(p1, "t1");
        Thread t2 = new Thread(m1, "t2");
        t1.start();
        t2.start();
    }
}

Output
======
i = 0 In thread executeInstructions of processor classThread[t1,5,main]
i = 1 In thread executeInstructions of processor classThread[t1,5,main]
i = 2 In thread executeInstructions of processor classThread[t1,5,main]
i = 3 In thread executeInstructions of processor classThread[t1,5,main]
i = 4 In thread executeInstructions of processor classThread[t1,5,main]
i = 5 In thread executeInstructions of processor classThread[t1,5,main]
i = 0 In thread checkMemory of memory classThread[t2,5,main]
i = 1 In thread checkMemory of memory classThread[t2,5,main]
i = 2 In thread checkMemory of memory classThread[t2,5,main]
i = 3 In thread checkMemory of memory classThread[t2,5,main]
i = 4 In thread checkMemory of memory classThread[t2,5,main]
i = 5 In thread checkMemory of memory classThread[t2,5,main]

The above program compiles and runs successfully to produce a desired expected output. As mentioned, we have two classes, viz processor and memory class. Both the classes implement Runnable interface which means we will be creating threads from both these classes. Class processor calls executeInstruction() from run method whereas class memory calls checkMemory() from run method. Both the methods viz. executeInstruction() and checkMemory() have a synchronized block each of which synchronizes over one and only one objLock because that's the object we pass to each object via the constructor at the time of creation of memory object m1 and processor object p1 inside main().

We create thread t1 out of processor object p1 [of class processor]and t2 out of memory object m1 [of class memory]. Next, t1 and t2 are started. The moment t1 gets a time slice, it acquires a lock on objLock and starts executing forloop within executeInstructions(). Since t1 owns the lock on objLock, t2 has to wait until t1 releases the lock. Once t1 completes the execution of for loop, it releases the objLock. Now t2 takes over and completes.

This way, we are able to synchronize synchronize threads t1 and t2 that are created out of two different objects viz. p1 and m1 which belong to totally different classes viz. processor and memory respectively.

Points of Interest

Two or more threads will synchronize if they have one and only one object lock in common.

History

  • 17th June, 2021: Initial revision

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Chetan Kudalkar
Software Developer (Senior)
India India
I am a Software engineer with around 7+ years of experience. Most of my experience is in Storage technology.

Comments and Discussions

 
QuestionYour Series Pin
Sean Ewington18-Jun-21 3:34
editorSean Ewington18-Jun-21 3:34 
AnswerRe: Your Series Pin
Chetan Kudalkar19-Jun-21 0:09
MemberChetan Kudalkar19-Jun-21 0:09 
GeneralRe: Your Series Pin
Sean Ewington21-Jun-21 2:49
editorSean Ewington21-Jun-21 2:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.