Hi I have a class with multiple methods in which I require synchronized blocks in all of the methods like this:
public class Test2 { private Object mutex=new Object(); private OtherClass obj=new OtherClass(); public void method1(){ //do some stuff synchronized (mutex) { obj.//some method //do some stuff } //do other stuff } public void method2(){ //do some stuff synchronized (mutex) { obj.//some method //do some stuff } //do other stuff } public void method3(){ //do some stuff synchronized (mutex) { obj.//some method //do some stuff } //do other stuff } public void method4(){ //do some stuff synchronized (mutex) { obj.//some method //do some stuff } //do other stuff } } I am using mutex to synchronize the blocks, so what happens if method1 is being used, the other method2 synchronized block waits until the flow comes out of the synchronized block of method1.
I dont want this to happen, so what should i do? I know that as I am using mutex for all the methods, so it locks the method2 synchronized block. I want to know what should I do to remove this? Should I create member variables for each method to use, or is there another way around this?
I want the other thread to wait only if the same method is called.. like if two threads class mehod1 so the second thread should wait. but if the second thread calls method2 it should not wait.
method2to do? Skip the block? Then synchronized is not what you are looking for...