0

I am a beginner in Java language. I have a client server application. In this application, there is a need for mutual exclusion for the resources to be accessed onto the server by multiple clients.

I am trying to achieve mutual exclusion by using a lock variable. But I don't known why the lock variable doesn't get updated when the current thread is done with it's job without a println statement in the loop.

Below is the code snippet for the server.java file -

int shown = 0;
int value = server.lock;
while(value != 1) {
  if(shown == 0) {
      System.out.println("Server is busy. Please wait");
      shown++;
   }
   value = server.lock;
   // Below statement.
   System.out.print("\t");
  }
shown = 0;
server.lock--;

The lock variable is updated always to 1 whenever the work of the current thread is done

The code works perfectly with a println statement but doesn't work without it. Like the while keeps on repeating. I don't know why.

Any help is appreciated.

Thank you,

P. Parekh

Pm P
  • 27
  • 3
  • This seems to be the same as https://stackoverflow.com/q/25425130/217324, it means you have a memory visibility issue. Also using busy waiting is a really inefficient way to solve this. – Nathan Hughes Nov 13 '21 at 14:41
  • The compiler, the JRE, and even the hardware operate under the assumption that most code will not interact with other threads. That's the best strategy because allowing for interactions between threads slows things down, and in fact, _most_ of our code does _not_ depend on other threads. So, if some other thread happens to change the value of `server.lock`, there's no guarantee about when (or even, if _ever_) that the thread executing the loop in your example will "see" the change. If you want to ensure that the loop promptly sees it, then you'll have to take special measures... – Solomon Slow Nov 13 '21 at 15:11
  • ...In Java, those special measures are called "synchronization," and the literature talks about the "happens before relationships" that synchronization establishes. "Java synchronization" and "Java happens before" are good terms to search for in Google. – Solomon Slow Nov 13 '21 at 15:13

0 Answers0