FutureTask
BackgroundTask
Android Development
Async Programming
Android Concurrency

How to implement .get feature with FutureTask or BackgroundTask using android?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If you want a .get()-style result in Android, the main rule is simple: background work can block, the UI thread cannot. FutureTask can give you a synchronous-looking get() API, but you need to structure it so the waiting happens off the main thread and the result is posted back safely.

What FutureTask.get() Really Does

FutureTask.get() blocks until the background computation finishes or fails. That behavior is fine on a worker thread, but it is dangerous on Android’s main thread because it can freeze the UI and trigger an Application Not Responding error.

A minimal Java example:

java
1Callable<String> work = () -> {
2    Thread.sleep(1000);
3    return "done";
4};
5
6FutureTask<String> task = new FutureTask<>(work);
7new Thread(task).start();
8
9String result = task.get(); // blocks until finished

That last line is only safe if it is not executed on the UI thread.

A Safe Android Pattern with ExecutorService

On Android, a practical pattern is:

  • run the work on an executor
  • wait for the result on a background thread if needed
  • post the final UI update to the main thread
java
1import android.os.Bundle;
2import android.os.Handler;
3import android.os.Looper;
4import android.widget.TextView;
5import androidx.appcompat.app.AppCompatActivity;
6import java.util.concurrent.Callable;
7import java.util.concurrent.ExecutorService;
8import java.util.concurrent.Executors;
9import java.util.concurrent.FutureTask;
10
11public class MainActivity extends AppCompatActivity {
12    private final ExecutorService executor = Executors.newSingleThreadExecutor();
13    private final Handler mainHandler = new Handler(Looper.getMainLooper());
14
15    @Override
16    protected void onCreate(Bundle savedInstanceState) {
17        super.onCreate(savedInstanceState);
18
19        TextView textView = new TextView(this);
20        setContentView(textView);
21
22        FutureTask<String> task = new FutureTask<>(createWork());
23        executor.execute(task);
24
25        executor.execute(() -> {
26            try {
27                String value = task.get();
28                mainHandler.post(() -> textView.setText(value));
29            } catch (Exception e) {
30                mainHandler.post(() -> textView.setText(e.getMessage()));
31            }
32        });
33    }
34
35    private Callable<String> createWork() {
36        return () -> {
37            Thread.sleep(1000);
38            return "Loaded from background";
39        };
40    }
41}

This preserves the get() behavior without blocking the main thread.

Do Not Use get() as a UI Shortcut

A common mistake is to write code that looks simple but blocks the screen:

java
1FutureTask<String> task = new FutureTask<>(() -> repository.loadName());
2new Thread(task).start();
3
4String value = task.get(); // bad if this runs on the main thread
5textView.setText(value);

The problem is not FutureTask itself. The problem is where get() is called.

If all you need is “run work in the background and update the screen,” a callback-style flow is often clearer than forcing a blocking call into the design.

What “BackgroundTask” Usually Means Today

Older Android code often used AsyncTask for this kind of workflow. That pattern is now outdated for new code. In current Android apps, the common replacements are:

  • 'ExecutorService plus Handler'
  • Kotlin coroutines
  • WorkManager for deferrable scheduled work

If your project is Java-based and already uses executors, FutureTask is a reasonable low-level primitive. If you are working in Kotlin, coroutines usually produce a cleaner API than manually coordinating get(), threads, and handlers.

Timeouts and Cancellation Matter

A useful part of the Future API is that you do not have to wait forever. You can set a timeout or cancel the work if the screen goes away.

java
1import java.util.concurrent.FutureTask;
2import java.util.concurrent.TimeUnit;
3import java.util.concurrent.TimeoutException;
4
5FutureTask<String> task = new FutureTask<>(() -> "result");
6new Thread(task).start();
7
8try {
9    String value = task.get(2, TimeUnit.SECONDS);
10    System.out.println(value);
11} catch (TimeoutException e) {
12    task.cancel(true);
13}

That is especially important on Android where activities and fragments can be destroyed while background work is still running.

Choose the Right Abstraction

Use FutureTask when you specifically want:

  • a Callable
  • cancellation
  • timeout handling
  • a Future result object

Do not use it just to imitate synchronous code on the UI thread. If the architecture wants a one-shot async result, a callback or coroutine often expresses the intent more clearly.

Common Pitfalls

  • Calling get() on the main thread and freezing the UI.
  • Updating views directly from the worker thread instead of posting back to the main thread.
  • Using old AsyncTask patterns for new code when executor-based or coroutine-based designs are clearer.
  • Forgetting to cancel or ignore results when the activity or fragment is no longer active.
  • Treating FutureTask as a threading strategy by itself instead of pairing it with a proper executor.

Summary

  • 'FutureTask.get() blocks, so it must not run on Android’s main thread.'
  • A safe pattern is to execute the task on a worker and post the result back to the UI thread.
  • 'FutureTask is useful when you need timeout, cancellation, or an explicit Future.'
  • For many Android apps, callbacks or coroutines are a better fit than blocking result retrieval.
  • The real goal is not “use .get() everywhere,” but “get background results without freezing the UI.”

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.