FutureTask in Android, wait for a thread to execute the next one This code is executed on a background service every 60 seconds on an Android app. Each class instantiated on FutureTask (WifiInfoFetch and WifiApResults) contains an insert to an SQLite database. We changed the original implementation (without a FutureTask) as we think the first insert was still locking the database when the second one tried to do its insert as they were executed very close to each other.

I think that with the code below, the second thread should wait until the first one is finished to start. Is this true? Also, what happens if for any reason thread 1 does not finish? Is there a way to set a timeout to interrupt it?

WifiInfo wifi = wifiManager.getConnectionInfo();
if (wifi == null) return;

WifiInfoFetch wifiInfo = new WifiInfoFetch(getApplicationContext(), wifi);
WifiApResults scanResults = new WifiApResults(getApplicationContext(), wifiManager.getScanResults());

FutureTask&lt;String&gt; futureWifiInfo = new FutureTask&lt;&gt;(wifiInfo);
FutureTask&lt;String&gt; futureScanResults = new FutureTask&lt;&gt;(scanResults);

ExecutorService executor = Executors.newFixedThreadPool(2);
try {
    executor.submit(futureWifiInfo).get();
    executor.submit(futureScanResults);
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}


Thanks!
There is no need for the FutureTask, the executor service will create a future that you can use to wait on the task and get the result (if any).

executor.submit(futureWifiInfo).get();


This is basically the same as just calling futureWifiInfo.run(); (or call) In other words you aren't quite there yet with making this properly asynchronous.

It does let you set a timeout on the get simply by adding the timeout parameters:

Future&lt;String&gt; futureWifiInfo = executor.submit(wifiInfo);
try {
    futureWifiInfo.get(1, TimeUnit.SECONDS);
    executor.submit(scanResults);

} catch (TimeoutException e) {
    // get timed out -&gt; cancel it
    futureWifiInfo.cancel(true);

} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}