Kapil Devmurari
Kapil Devmurari

Reputation: 159

Same objects in multiple Threads for Synchronization

I am working on multi-threading environment where I have below scenario.

I am creating 5 threads and passing same object into all threads. (just action value is different)

MyClass myclass = new MyClass();
myclass.id("123");
myclass.setAction("Deposit");

MyClass myclass1 = new MyClass();
myclass1.id("123");
myclass1.setAction("withdraw");

MyThread t1 = new MyThread(myclass) // in my Thread Class I have implemented Runnable interface and over ride run method and from run method i am calling transaction method
MyThread t2 = new MyThread(myclass)
MyThread t3 = new MyThread(myclass)
MyThread t4 = new MyThread(myclass1)
MyThread t5 = new MyThread(myclass1)

t1.start();
t2.start();
t3.start();
t4.start();
t5.start();

public void transaction(MyClass myclass) {
    synchronized(myclass.id()) {
        // I am writing my code
    }
}

I have two different objects but id is same, will these threads work in sync manner or I have create two new instance so it will execute in async?

Thank you

Upvotes: 1

Views: 453

Answers (1)

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 18959

Since String.class is immutable the following may not work.

synchronized(myclass.id()){
        // I am writing my code
    }

Because the String passed may be another object reference in some other part of application from the String Object for which you have created your original object. So you can't use the monitor lock on that object with safety to synchronize threads.

Edit: You could try to keep on that singleton service class which you refer in comments as a field a ConcurentHashMap and use the String id that you want as key, where the keys of map are always compared with equals and as a value to the map use new Object() so you have a specific instance in Heap memory that no one else uses for each key string id and you base your lock on that and only on that instance.

This would have the drawback that this map can grow very large for each String id that you have added in order to have a specific lock and may be tricky to clean it up.

Upvotes: 3

Related Questions