Skip to content

Synchronisation: Two instances using the same monitor object

Devrath edited this page Feb 14, 2024 · 1 revision

Observation

  • Now since the methods of increment() and decrement() use the same monitor object, They do not interfere with each other

Output

<---------------Start of execution--------------->

Tag(Tag-1) --> Incremented 1 by {Thread-0}
Tag(Tag-2) --> Decremented -1 by {Thread-1}
Tag(Tag-1) --> Incremented 2 by {Thread-0}
Tag(Tag-2) --> Decremented -2 by {Thread-1}
Tag(Tag-1) --> Incremented 3 by {Thread-0}
Tag(Tag-2) --> Decremented -3 by {Thread-1}

Tag(Tag-1) -->Result of the counter:-> 3
Tag(Tag-2) -->Result of the counter:-> -3

<---------------End of execution----------------->

Code

fun main(args: Array<String>) {

    println("<---------------Start of execution--------------->")
    println()

    val tag1 = "Tag-1"
    val tag2 = "Tag-2"

    val sharedResource1 = SharedResource(tag1)
    val sharedResource2 = SharedResource(tag2)

    // Create a thread-1
    val runnable1 = Runnable {
        for (i in 1..3){
            sharedResource1.increment()
            Thread.sleep(20)
        }
    }

    // Create a thread-2
    val runnable2 = Runnable {
        for(i in 1..3){
            sharedResource2.decrement()
            Thread.sleep(20)
        }
    }

    val thread1 = Thread(runnable1)
    val thread2 = Thread(runnable2)

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()

    println()
    println("Tag($tag1) -->Result of the counter:-> ${sharedResource1.getResult()}")
    println("Tag($tag2) -->Result of the counter:-> ${sharedResource2.getResult()}")
    println()

    println("<---------------End of execution----------------->")

}



class SharedResource(val tag : String) {

    private var counter = 0

    fun increment(){
        synchronized(MonitorObject) {
            counter++
            println("Tag($tag) --> Incremented $counter by {${Thread.currentThread().name}}")
        }
    }

    fun decrement(){
        synchronized(MonitorObject) {
            counter--
            println("Tag($tag) --> Decremented $counter by {${Thread.currentThread().name}}")
        }
    }

    @Synchronized
    fun getResult(): Int {
        return counter
    }

    companion object {
        private val MonitorObject = Any()
    }

}