Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java asynchronous method call

I have already one thread that has to do following work:

public class DetectionHandler extends TimerTask {

@Override
public void run() {
bluetoothAddresses = BluetoothModule.scanAddresses();
wiFiAddresses = WiFiModule.scanAddresses();
...//when scanning is finished, continue work
}

I would like that scanning to be parallel. So I assume that I have to call that two methods asynchronously. And when that scanning is finished, then I can continue work in DetectionHandler class.

I've tried the way that BluetoothModule and WiFiModule implements Runnable but had no luck. Tnx

like image 993
vale4674 Avatar asked Dec 30 '25 11:12

vale4674


2 Answers

Using ExecutorService you can write something like this:

ArrayList<Callable<Collection<Address>>> tasks = new ArrayList<Callable<Collection<Address>>>();
tasks.add(new Callable<Collection<Address>>() {
  public Collection<Address> call() throws Exception {
    return BluetoothModule.scanAddresses();
  }
});
tasks.add(new Callable<Collection<Address>>() {
  public Collection<Address> call() throws Exception {
    return WiFiModule.scanAddresses();
  }
});

ExecutorService executorService = Executors.newFixedThreadPool(2);
List<Future<Collection<Address>>> futures = executorService.invokeAll(tasks);
like image 84
Eugene Kuleshov Avatar answered Jan 01 '26 04:01

Eugene Kuleshov


Get an ExecutorService from Executors and give it a FutureTask.

You can then wait for the results by calling the blocking get() on the returned Future. The scans will run parallel but your run method (shown here) will still wait for the scans to be finished.

A bit like:

     FutureTask<List<Address>> btFuture =
       new FutureTask<List<Address>>(new Callable<List<Address>>() {
         public List<Address> call() {
           return BluetoothModule.scanAddresses();
       }});
     executor.execute(btFuture);

     FutureTask<List<Address>> wfFuture =
       new FutureTask<List<Address>>(new Callable<List<Address>>() {
         public List<Address> call() {
           return WifiModule.scanAddresses();
       }});
     executor.execute(wfFuture);

    btAddresses = btFuture.get(); // blocks until process finished
    wifiAddresses = wfFuture.get(); // blocks

Be carefull though, get will return whatever call returns. Exceptions are wrapped in an ExecutionException.

like image 25
extraneon Avatar answered Jan 01 '26 04:01

extraneon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!