LearnFrenzy
Sign in Take a free test

Java Programming · Topic 27 of 28

Concurrency and Executors

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Programs & Examples

Concurrency and Executors · Study material

A flight-fare aggregator with CompletableFuture

Four airline APIs are queried in parallel; failures become "no fare", a slow API is cut off with completeOnTimeout, and the cheapest fare is chosen.

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

record Quote(String airline, int price) { }

public class Main {
    static Quote ask(String airline, int price, int delayMs, boolean fail) {
        try { Thread.sleep(delayMs); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        if (fail) throw new IllegalStateException(airline + " API down");
        return new Quote(airline, price);
    }

    public static void main(String[] args) {
        try (ExecutorService io = Executors.newFixedThreadPool(4)) {
            List<CompletableFuture<Quote>> calls = List.of(
                CompletableFuture.supplyAsync(() -> ask("IndiGo", 5499, 80, false), io),
                CompletableFuture.supplyAsync(() -> ask("Air India", 6120, 50, false), io),
                CompletableFuture.supplyAsync(() -> ask("Akasa", 4999, 60, true), io),                  // fails
                CompletableFuture.supplyAsync(() -> ask("Vistara", 4799, 3000, false), io)               // too slow
                    .completeOnTimeout(new Quote("Vistara", Integer.MAX_VALUE), 300, TimeUnit.MILLISECONDS));

            List<CompletableFuture<Quote>> safe = calls.stream()
                .map(f -> f.exceptionally(ex -> new Quote("error: " + (ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage()), Integer.MAX_VALUE)))
                .toList();
            CompletableFuture.allOf(safe.toArray(new CompletableFuture<?>[0])).join();      // wait for all

            List<Quote> quotes = safe.stream().map(CompletableFuture::join).toList();
            quotes.forEach(q -> System.out.println(q.airline() + (q.price() == Integer.MAX_VALUE ? " (no fare)" : " Rs " + q.price())));
            quotes.stream().filter(q -> q.price() != Integer.MAX_VALUE).min(Comparator.comparingInt(Quote::price))
                  .ifPresent(q -> System.out.println("cheapest: " + q.airline() + " Rs " + q.price()));
        }
    }
}

Output

IndiGo Rs 5499
Air India Rs 6120
error: Akasa API down (no fare)
Vistara (no fare)
cheapest: IndiGo Rs 5499

Callable tasks on a fixed thread pool

The executor example computes six slow squares on three threads and sums them through their Futures.

Latch, semaphore and barrier

The synchronizer example waits for services to start, limits concurrent tasks to two, and runs workers through two barrier phases.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links