title: Java - synchronous callback
body: <p>I have the following code which is executed asynchronously. I would like to make it synchronous in order to follow some logical flow but I cannot work out how.</p>
  
  <p>You will see that <code>scanning</code> is set to <code>true</code> to indicate that the method is still working, at the beginning - I then initiate a <code>findPrinters(...)</code> command - this contains a DiscoveryHandler which runs asynchronously - <code>foundPrinter()</code> is called each time an item is discovered. <code>discoveryFinished()</code> is when the discovery process is successfully completed, and <code>discoveryError(...)</code> is called whenever an error occurs.</p>
  
  <p>I rely on something being set in my DiscoveryHandler before I would like to return from this method. Hence why I have <code>while (scanning)</code> underneath it. But this feels like a hack to me, and not the correct way of doing things. I cannot get <code>wait()</code> and <code>notify()</code> working. Can someone tell me what the correct way to do this is please?</p>
  
  <pre><code>private boolean findPrinter(final Context ctx) {
      try {
          scanning = true;
          BluetoothDiscoverer.findPrinters(ctx, new DiscoveryHandler() {
  
              public void foundPrinter(DiscoveredPrinter device) {
                  if (device instanceof DiscoveredPrinterBluetooth) {
                      DiscoveredPrinterBluetooth btDevice = (DiscoveredPrinterBluetooth) device;
  
                      if (btDevice.friendlyName.startsWith("XXXX")) {
                          try {
                              connection = new BluetoothConnection(btDevice.address);
                              connection.open();
  
                              if (connection.isConnected()) {
                                  address = btDevice.address;
                              }
                          } catch (Exception ex) {
  
                          }
                      }
                  }
              }
  
              public void discoveryFinished() {
                  scanning = false;
              }
  
              public void discoveryError(String arg0) {
                  scanning = false;
              }
          });
      } catch (Exception ex) {
  
      }
  
      while (scanning) {}
  
      return false;
  }
  </code></pre>