Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1960
  • Last Modified:

ManualResetEvent alternative in Java

I have a Java application that communicates with a scales through TCP.
It uses two threads:

class ScalesCommunication {
   // called by thread 1
   void readLoop() {
      // connects to the scales
      // reads data sent by it
   }

   // called by thread 2
   String sendCommand(String command) {
       // sends a command and waits for its answer
   }
}

I would like to solve some synchronization problems
- sendCommand should wait until connection is built up
- after a command has been sent, the answer should be waited for

One thread is not enough, because I should deal with asynchronous messages such as keypresses. The interface is given, I can't separate building up the connection from reading incoming data.
In .NET this kind of synchronization can easily be solved by means of ManualResetEvent synchronization objects. Is there any alternative in Java?
0
pallosp
Asked:
pallosp
1 Solution
 
Ravi SinghSenior Software EngineerCommented:
Hi, you can achieve synchronization using the java.util.concurrent.Semaphore class (use 0 permit).

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Semaphore.html

Example below shows you how to solve the first sync problem, the other will be similar:

import java.util.concurrent.Semaphore;

class ScalesCommunication {

   private static Semaphore sem = new Semaphore(0);

   // called by thread 1
   void readLoop() {
      //...

      //after connection established, release semaphore (value incremented by 1)
      sem.release();
   }

   // called by thread 2
   String sendCommand(String command) {

       sem.acquire(); // thread waits here if sem value == 0

       // at this point connection is established
       //...
   }
}
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now