LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Exercise 2 of 4

Concurrency and Executors Predict the Output

  • 20 questions
  • Page 2 of 2
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

Read each Java program and choose what it prints. The programs print only deterministic results (in submission order or aggregated). Every program was compiled and run on Java 21.

Question 11 Easy

What is the output of the following Java program?

Main.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) {
        AtomicInteger visits = new AtomicInteger();
        try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
            for (int i = 0; i < 1000; i++) pool.submit(visits::incrementAndGet);
        }
        System.out.println(visits.get() + " " + visits.addAndGet(-500) + " " + visits.getAndIncrement() + " " + visits);
    }
}
A 1000 500 500 501
B 1000 500 501 501
C less than 1000 500 500 501
D 1000 -500 500 501
Question page & discussion
Question 12 Medium

What is the output of the following Java program?

Main.java
import java.util.concurrent.atomic.AtomicReference;

public class Main {
    public static void main(String[] args) {
        AtomicReference<String> status = new AtomicReference<>("NEW");
        boolean a = status.compareAndSet("NEW", "PAID");
        boolean b = status.compareAndSet("NEW", "CANCELLED");     // fails: it is no longer NEW
        String c = status.getAndSet("SHIPPED");
        String d = status.updateAndGet(s -> s + "!");
        System.out.println(a + " " + b + " " + c + " " + d);
    }
}
A true false PAID SHIPPED!
B true true CANCELLED SHIPPED!
C false false NEW SHIPPED!
D true false SHIPPED SHIPPED!
Question page & discussion
Question 13 Medium

What is the output of the following Java program?

Main.java
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        List<String> lines = List.of("a b a", "b c", "a c c", "b");
        ConcurrentHashMap<String, Integer> freq = new ConcurrentHashMap<>();
        try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
            for (String line : lines) pool.submit(() -> { for (String w : line.split(" ")) freq.merge(w, 1, Integer::sum); });
        }
        System.out.println(new TreeMap<>(freq) + " " + freq.reduceValues(1, Integer::sum));
    }
}
A {a=3, b=3, c=3} 9
B {a=3, b=3, c=3} 3
C {a=2, b=3, c=3} 8
D It varies
Question page & discussion
Question 14 Medium

What is the output of the following Java program?

Main.java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch done = new CountDownLatch(4);
        AtomicInteger checked = new AtomicInteger();
        ExecutorService pool = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 4; i++) pool.submit(() -> { checked.addAndGet(25); done.countDown(); });
        done.await();                           // returns when the count reaches 0
        System.out.println(checked.get() + "% " + done.getCount());
        done.countDown();                       // no effect once at zero
        System.out.println(done.getCount());
        pool.shutdown();
    }
}
A 100% 0 0
B 100% 0 -1
C 75% 1 0
D It varies
Question page & discussion
Question 15 Medium

What is the output of the following Java program?

Main.java
import java.util.concurrent.Semaphore;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Semaphore s = new Semaphore(3);
        s.acquire();
        s.acquire(2);
        boolean got = s.tryAcquire();          // no permits left: returns false immediately
        int avail = s.availablePermits();
        s.release(2);
        System.out.println(got + " " + avail + " " + s.availablePermits() + " " + s.tryAcquire());
    }
}
A false 0 2 true
B true 0 2 true
C false 1 3 true
D false 0 2 false
Question page & discussion
Question 16 Medium

What is the output of the following Java program?

Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> q = new ArrayBlockingQueue<>(2);
        List<String> got = new ArrayList<>();
        Thread producer = new Thread(() -> {
            try { for (String s : new String[]{"o1", "o2", "o3", "o4", "STOP"}) q.put(s); } catch (InterruptedException e) { }
        });
        Thread consumer = new Thread(() -> {
            try { for (String s; !(s = q.take()).equals("STOP"); ) got.add(s.toUpperCase()); } catch (InterruptedException e) { }
        });
        producer.start(); consumer.start();
        producer.join(); consumer.join();
        System.out.println(got + " " + q.isEmpty() + " " + q.offer("x") + q.offer("y") + q.offer("z"));
    }
}
A [O1, O2, O3, O4] true truetruefalse
B [O1, O2, O3, O4] true truetruetrue
C [O1, O2] false truefalsefalse
D It varies
Question page & discussion
Question 17 Medium

What is the output of the following Java program?

Main.java
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Thread holder = new Thread(() -> {
            lock.lock();
            try { Thread.sleep(300); } catch (InterruptedException e) { } finally { lock.unlock(); }
        });
        holder.start();
        while (!lock.isLocked()) Thread.onSpinWait();
        boolean first = lock.tryLock();
        holder.join();
        boolean second = lock.tryLock();
        lock.lock();                                   // re-entrant: same thread locks again
        System.out.println(first + " " + second + " " + lock.getHoldCount() + " " + lock.isHeldByCurrentThread());
        lock.unlock(); lock.unlock();
    }
}
A false true 2 true
B true true 2 true
C false true 1 true
D false false 0 false
Question page & discussion
Question 18 Hard

What is the output of the following Java program?

Main.java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
        CountDownLatch bothReading = new CountDownLatch(2), release = new CountDownLatch(1);
        Runnable reader = () -> {
            rw.readLock().lock();
            try { bothReading.countDown(); release.await(); } catch (InterruptedException e) { }
            finally { rw.readLock().unlock(); }
        };
        Thread r1 = new Thread(reader), r2 = new Thread(reader);
        r1.start(); r2.start();
        bothReading.await();                                   // two readers hold the lock at the SAME time
        int readers = rw.getReadLockCount();
        boolean writerCouldEnter = rw.writeLock().tryLock();    // a writer must wait for all readers
        release.countDown();
        r1.join(); r2.join();
        boolean writerNow = rw.writeLock().tryLock();
        System.out.println(readers + " " + writerCouldEnter + " " + writerNow + " " + rw.isWriteLocked());
    }
}
A 2 false true true
B 1 false true true
C 2 true true true
D 2 false false false
Question page & discussion
Question 19 Medium

What is the output of the following Java program?

Main.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
    public static void main(String[] args) throws Exception {
        Thread v = Thread.ofVirtual().name("job-1").unstarted(() -> { });
        Thread p = Thread.ofPlatform().name("job-2").unstarted(() -> { });
        Future<Boolean> f;
        try (ExecutorService exec = Executors.newVirtualThreadPerTaskExecutor()) {
            f = exec.submit(() -> Thread.currentThread().isVirtual());
        }
        System.out.println(v.isVirtual() + " " + p.isVirtual() + " " + v.isDaemon() + " " + f.get() + " " + v.getState());
    }
}
A true false true true NEW
B true false false true NEW
C true true true true NEW
D true false true false RUNNABLE
Question page & discussion
Question 20 Hard

What is the output of the following Java program?

Main.java
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class Main {
    static class MaxTask extends RecursiveTask<Integer> {
        private static final long serialVersionUID = 1L;
        final int[] a; final int lo, hi;
        MaxTask(int[] a, int lo, int hi) { this.a = a; this.lo = lo; this.hi = hi; }
        @Override protected Integer compute() {
            if (hi - lo <= 4) { int m = Integer.MIN_VALUE; for (int i = lo; i < hi; i++) m = Math.max(m, a[i]); return m; }
            int mid = (lo + hi) / 2;
            MaxTask left = new MaxTask(a, lo, mid);
            left.fork();
            int rightMax = new MaxTask(a, mid, hi).compute();
            return Math.max(left.join(), rightMax);
        }
    }

    public static void main(String[] args) {
        int[] data = {12, 45, 7, 89, 23, 56, 91, 3, 67, 34, 88, 19, 76, 41};
        System.out.println(new ForkJoinPool(2).invoke(new MaxTask(data, 0, data.length)));
    }
}
A 91
B 89
C 88
D 14
Question page & discussion
Up next · Exercise 3Find the Error10 questions

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links