Question

I have a condition as mentioned below, where i need multiple clients to access my server. i have my code which goes as follows.

main(){
new thread(new class()).start();
}  

void run(){
xyz();
}

xyz(){
     switch(){
      case 1:
        read()
        break;
      case 2:
        write()  
     }
}

i want to make sure that when write() is being executed by one thread. read() should not be blocked. I have many such functions which are interlinked with each other. how can i make sure that that the functions are synchronized? should i remove the switch case and use synchronized blocks? or is there any other way?

Was it helpful?

Solution

Remove the switch? But "switch" has nothing to do with synchronization. Sounds like, maybe your real question is about what objects to lock on, and how many, and when.

You said, "I want to make sure that when write() is being executed by one thread. read() should not be blocked."

Your code already seems to do that. You have not shown us anything that would prevent a read() call from happening at the same time as a write() call. What are you trying to prevent? If you only want to prevent concurrent write() calls, but you don't care what happens concurrently with a read() call, then that might look like this:

private Object writerLock = new Object();

xyz(...) {
    //same as in your example
}

private ... read(...) {
    ...
}

private ... write(...) {
    synchronized(writerLock) {
        ...
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top