Consider i have a 2 objects of a same class and there are 2 threads running on each object.And there is a method test() in the class.How to ensure that only thread can call this method.
I have considered the option of making the method as synchronized but since there are two different objects and the lock will be object level how can i make sure only one thread at a time can call the method.
Many people would regard plain synchronisation as old‑fashioned coding. Since Java5 (getting on for thirteen years ago), most people would probably use a Lock instance.That can lock multiple methods simultaneously in the order they are called. You do have to use a finally. You cannot use try with resources. The finally must come at the very end of the method.
Only allowing one instance of the class to have a method accessed from one thread at a time sounds a strange requirement. Please explain what that means and why you want to do it. My object‑oriented‑thinking brain cell is getting all confused about that. If you have two objects, why can you not call a method on each simultaneously? Why pass an Object from elsewhere? That doesn't seem to comply with the single responsibility principle. The object should take care of itself, without requiring outside code provide the lock for it. I still think the lock should be a field of the Foo class; if you really only want one lock, then make it static. Again, I am thinking is that really object‑oriented?
Please explain why you have this requirement, or (far better) is it simply a what if...sort of question?
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop