Sobes.tech
Junior — Middle

How to implement asynchronous task execution in Java?

sobes.tech AI

Answer from AI

In Java (including on Android), there are several approaches to perform asynchronous tasks:

  1. Thread / Runnable: Create a new thread to execute a task.

  2. ExecutorService: Managed thread pool for executing tasks.

  3. AsyncTask (deprecated in Android): Allowed executing tasks in the background with UI updates.

  4. CompletableFuture (Java 8+): Enables writing asynchronous code with chains of actions.

  5. RxJava: A library for reactive programming with support for asynchrony.

  6. Coroutines (Kotlin): A modern way of asynchronous programming on Android.

Example using ExecutorService:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
    // Long operation
    System.out.println("Executing in background");
    // After execution, UI can be updated via Handler or runOnUiThread
});
executor.shutdown();

This method allows executing tasks in a separate thread without blocking the main application thread.

How to implement asynchronous task execution in Java… - sobes.tech