title: Asynchronous Listener Synchronization Java HID
body: <p>I tried to look around for some time, but I was not able to find an answer to my problem.
  I am currently writing a Java program that will be used to read and update the firmware of an HID device. I am using the pureHID java libraries to communicate with my device and everything is working fine.</p>
  
  <p>The only problem I am currently experiencing, and I was not able to fix, concerns the synchronization of events.</p>
  
  <p>I will give you an example.
  When copying the firmware currently installed on the device, I am using the following method</p>
  
  <pre><code>dev.setOutputReport((byte) 0, packet_to_send, BUFFER_SIZE);
  </code></pre>
  
  <p>The answer from the unit will come in the form of an event received by the listener attached to the device manager, namely the following listener will be invoked</p>
  
  <pre><code>onInputReport() /* Something will happen */
  </code></pre>
  
  <p>My problem is that SOMETIMES, probably because of concurrent writing/listening invocation, the program completely freeze, without any exception nor any error signaled.</p>
  
  <p>To fix the problem, I tried to implement a simple Lock mechanism, with the Lock being released only when a reply is received; but unfortunately it may happen that the reply packet sometimes is lost thus blocking me in a deadlock.</p>
  
  <p>One possible solution I though would be to use a timer which will release the lock automatically after x milliseconds if it is not released (the reply will arrive within 10ms or will not arrive), but I do not know how to create an independent thread to manage the timer.</p>
  
  <p>Can you please help me fixing this problem, or suggest me another concurrency mechanism which I can use to synchronize the two blocks OR to re-transmit the message, if a reply is lost?</p>
  
  <p>Thank you very much to anyone helping.</p>
  
  <p>Lorenzo</p>