Threads ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-11-27

Threads. Practical Tasks

Two threads each run count++ 100,000 times on a shared field, and the program prints not 200,000 but a smaller number — a different one on every run. No exception, no compiler warning. A bug like this is hard to grasp from a description: you need to reproduce it and fix it with your own hands once. That is what the exercises below are for.

This page collects Java multithreading exercises: 21 hands-on concurrency tasks, from creating your first thread with Thread and Runnable to ExecutorService, CompletableFuture, concurrent collections, synchronizers and virtual threads. The exercises go from easy to hard and build on the lessons of the Threads module, starting with the introduction to multithreading in Java. Every exercise comes with a hint and the expected output, so you can check your result without a reference solution. The last three are Java concurrency practice problems that interviewers often give.

What to Review Before You Start

Each exercise practices one or two lessons of the module. If an exercise does not work out, go back to the lesson from the table; the hints under the exercises also link to the exact sections.

Create a Thread by Extending the Thread Class

The very first way to run code in a separate thread is to extend the Thread class.

  1. Create a NewThread class that extends Thread.
  2. Override the run() method: in a for loop, print the * character to the console 100 times.
  3. In main(), create an instance of the class and start a new thread.
  4. Right after starting it, print the - character 100 times from main() in the same kind of loop.

Expected output: 100 asterisks and 100 hyphens on the console. The order is not fixed: the characters of the two threads come in blocks or mixed together, and the picture changes from run to run.

Hint

Start the thread with start(), not run(). A direct call to run() executes the loop in the main thread, and the asterisks always come strictly before the hyphens. The difference is explained in start() vs run().

Create Threads with the Runnable Interface

  1. Create a Counter class that implements the Runnable interface.
  2. Override run(): in a for loop, go through the numbers from 0 to 100 and print the ones divisible by 10, together with the thread name, Thread.currentThread().getName().
  3. After each print, pause for 100 ms with the static method Thread.sleep().
  4. Create three threads with the same Counter object and the names first, second, third, and start them.

Expected output: each thread prints 11 lines (0, 10, …, 100), 33 lines in total in about 1.1 seconds. The lines of the threads are mixed, for example: first: 0, third: 0, second: 0, second: 10…

Note

Thread.sleep() throws the checked InterruptedException, and run() of Runnable cannot declare it, so you have to catch it inside run(). Do not leave the catch block empty: restore the flag with Thread.currentThread().interrupt() and leave the loop (see how to handle InterruptedException).

You need to create three threads that modify the same object. Each thread prints one letter 100 times and then increments the character by 1: this way the first thread prints a, the second b, the third c. The output of one thread must not mix with the output of another.

  1. Create a class that extends Thread.
  2. Add a constructor that takes a StringBuilder object, so that all three thread objects get access to the same object.
  3. Override run(): it will contain a synchronized block that acquires the monitor of this StringBuilder object.
  4. Inside the synchronized block, print the StringBuilder 100 times, then increment the character by 1.
  5. In main(), create one StringBuilder object with the character a, then three instances of your class, and start the threads.

Expected output: 100 letters a, then 100 letters b, then 100 letters c. The order of the letters is always the same, although which of the three threads prints a is not known in advance.

Check yourself

You can increment the character like this: sb.setCharAt(0, (char) (sb.charAt(0) + 1)). Once the program works, remove synchronized and run it several times: the letters start to mix, and one letter may be printed twice 100 times or not at all — two threads manage to read the character before it is incremented.

MyQueue with Several Consumers

Change the MyQueue class from the lesson wait() and notify() in Java, where a producer and a consumer pass a number to each other with wait()/notify():

  1. Instead of int n, add a Queue<T> (make MyQueue generic) that holds the objects created by Producer.
  2. Limit the capacity of the queue, for example to five elements: the add method waits until there is room in the queue, the take method waits while the queue is empty.
  3. Add one more Consumer object that also runs in a separate thread.
  4. Print to the console which of the Consumer objects processed an object from the queue.
  5. Change the for loop to an infinite loop.

Expected output: lines like Sent: 1, Consumer-1 received: 1, Consumer-2 received: 2… Every object is processed by exactly one consumer: none is lost and none is processed twice. The program runs forever — stop it manually.

Where people usually go wrong

With two consumers, checking the condition with if before wait() stops working: a thread that wakes up may find that the other consumer has already taken the element, and get null from an empty queue. Wait in a while loop and wake threads with notifyAll() — see why wait() is called in a loop and notify() vs notifyAll().

Dining Philosophers

A classic deadlock problem. It is often given in interviews, because the “naive” solution hangs.

  1. Five silent philosophers sit around a round table, with a plate of spaghetti in front of each of them.
  2. Forks lie on the table between each pair of neighboring philosophers.
  3. Each philosopher can either eat or think.
  4. A philosopher can eat only while holding two forks — the one on the right and the one on the left.
  5. Taking each fork and putting it back on the table are separate actions that must be done one after another.

Write a program that simulates the dinner:

  • each philosopher is a separate thread, each fork is a shared object (a monitor or a ReentrantLock);
  • a philosopher repeats the cycle “think → take the forks → eat → put the forks down” 3 times; simulate thinking and eating with a pause of 50–100 ms;
  • first write the naive version — everyone takes the left fork, then the right one — and make it hang (a pause between taking the first and the second fork speeds up the deadlock);
  • then fix the program so that it always finishes.

Expected output: lines like Philosopher 2 is eating (1/3), and at the end All philosophers have eaten. The fixed version finishes in each of 20 runs in a row.

Hint

The deadlock comes from circular waiting: everyone holds the left fork and waits for the right one. Break the circle — let every philosopher take the fork with the lower number first; then one of them takes the forks in the reverse order, and the circle never closes. Other ways are tryLock() with a rollback or a Semaphore with four seats at the table. The conditions of a deadlock and how to avoid it are covered in How to Avoid Deadlock in Java.

Wait for Several Threads and Check Their States

Create three threads that “work” for different times: 300, 600 and 900 ms (simulate the work with Thread.sleep()).

  1. Before calling start(), print the state of each thread with getState().
  2. Start all three threads and print their states again right away.
  3. Wait for all threads to finish with join(), print the states once more, then the line “All threads finished” and how long main ran in milliseconds.

Expected output: NEW before the start and TERMINATED for all three after join(). Right after start(), the state can be RUNNABLE or TIMED_WAITING, depending on whether the thread has already reached sleep(). The total time is about 900 ms, not 1800: the threads run in parallel, and join() in effect waits for the longest one.

Check yourself

Call join() on each thread right after its start() — the time grows to about 1800 ms, because the threads now run one after another. What each state means is explained in the lesson Thread States in Java.

A Daemon Thread for a Background Heartbeat

Background service threads — connection checks, cache cleanup, the application’s “pulse” — are usually made daemons, so that they do not keep the program from exiting.

  1. Write a heartbeat thread that prints heartbeat and the current time every 500 ms in an infinite loop.
  2. Make it a daemon thread and start it.
  3. The main thread “works” for 2 seconds (Thread.sleep(2000)), prints “main finished” and ends.
  4. Remove setDaemon(true) and run the program again. Then put the call back, but after start().

Expected output: with a daemon, 4–5 heartbeat lines, then “main finished”, and the program ends. Without a daemon, heartbeat is printed forever. With setDaemon(true) after start(), you get an IllegalThreadStateException.

Easy to miss

A daemon is cut off mid-sentence: when the JVM exits, the finally block in its run() is not executed. That is why a daemon must not be trusted with writing a file or sending data; such work needs an ordinary thread with a proper shutdown (see what happens to a daemon when the JVM exits).

Stop a Thread with a volatile Flag

  1. Create a Worker implements Runnable class with a field boolean running = true and a stop() method that sets the flag to false.
  2. In run(), spin a while (running) loop that only increments a local iteration counter — no console output and no sleep(). After the loop, print “Stopped, iterations: N”.
  3. In main(), start the thread, call stop() after 1 second and wait for the thread with join().
  4. Run the program with a plain field, then declare the field volatile.

Expected output: with volatile, the thread always stops after about a second and prints the number of iterations (it depends on the machine). Without volatile, the program often hangs on HotSpot: the JIT is allowed to read the field once and never read it again. This is not guaranteed — sometimes the program finishes, but that does not make it correct.

Why no println

Printing to the console inside the loop often “fixes” the program without volatile: println() synchronizes internally, and the JIT no longer hoists the field read out of the loop. But that is luck, not a guarantee of the memory model. The breakdown is in The Visibility Problem.

Stop a Thread Gracefully with interrupt()

A worker thread takes tasks numbered 1, 2, 3… and spends 300 ms on each one (Thread.sleep(300)). A task counts as processed after the pause. Stop the thread from the outside so that it finishes cleanly and reports how much it managed to do.

  1. The work loop is while (!Thread.currentThread().isInterrupted()).
  2. Handle InterruptedException so that the thread leaves the loop instead of going on. In a finally block, print “Worker stopped, tasks: N”.
  3. In main(), call interrupt() after 1 second, then join(), and print the state of the thread.
  4. Move the pause into a helper method pause(long ms) that catches InterruptedException and does nothing. Make sure the thread no longer stops, then fix the method.

Expected output: three tasks are processed (the pauses end at 300, 600 and 900 ms, the interrupt arrives during the fourth one), then “Worker stopped, tasks: 3” and the state TERMINATED. With the “swallowing” pause() method, the thread runs forever.

Hint

When sleep() throws InterruptedException, the interrupt flag has already been cleared, so an empty catch loses the stop request. In pause(), either restore the flag with Thread.currentThread().interrupt() or declare throws InterruptedException. Why not Thread.stop() and how the flag works is explained in the lesson on interrupting a thread.

A Counter Without Lost Updates: synchronized vs AtomicInteger

Four threads each increment a shared counter 1,000,000 times. Write three versions of the counter and compare the result and the running time.

  1. UnsafeCounter — an int count field and an increment() method with count++, without synchronization.
  2. SyncCounter — the same count++, but the method is synchronized.
  3. AtomicCounter — AtomicInteger and incrementAndGet() (see atomic classes).
  4. For each version, start 4 threads, wait for them with join(), and print the final value and the time in milliseconds (System.nanoTime()).
  5. Optionally, add a fourth version on LongAdder.

Expected output: UnsafeCounter shows less than 4,000,000, and a different number on every run. SyncCounter and AtomicCounter always give exactly 4,000,000. The time depends on the CPU and the JVM, so draw conclusions from several runs, not from one.

How to measure fairly

The first run includes the JIT warm-up: run each version several times in a row and compare the last measurements. And do not try to fix UnsafeCounter with volatile — count++ stays non-atomic (see volatile and atomicity).

Word Frequency in Several Threads: ConcurrentHashMap

Count how many times each word occurs in a text, splitting the work between threads.

  1. Take a text of a few thousand words (you can repeat one paragraph in a loop) and split it into 4 parts.
  2. Each part is processed by a separate task in a pool of 4 threads: it converts the words to lower case and writes them to a shared ConcurrentHashMap<String, Integer> with merge(word, 1, Integer::sum).
  3. Wait for all tasks, sort the entries by descending frequency and print the 10 most frequent words.
  4. Check the result: the sum of all map values must equal the number of words counted in a single thread.
  5. Replace ConcurrentHashMap with HashMap, then go back to ConcurrentHashMap, but use a get() + put() pair instead of merge(). Compare the sums.

Expected output: with ConcurrentHashMap and merge(), the sums always match. With HashMap, the count is off, and some words may disappear from the map. With get() + put(), some increments are lost: each operation is atomic on its own, but the pair is not.

Hint

merge() performs “read – add – write” atomically for one key. The table of atomic methods is in Atomic Operations in ConcurrentHashMap. If the same word is updated very often, you can store a LongAdder in the map instead of an Integer.

Counting Lines in Files: ExecutorService, Callable and Future

You have a list of paths to text files. Count the lines in each file in parallel and print the total.

  1. Take 4–5 files (the .java files of your project will do) and add one path that does not exist to the list.
  2. For each file, submit a Callable<Long> task to a pool of 3 threads that counts the lines with Files.lines(path).count(); close the stream of lines in try-with-resources.
  3. Store the Future objects in a list and get the results with get() in the order in which you submitted the tasks.
  4. A read error in one file must not crash the program: print the file name and the cause, and include the other results in the total.
  5. Shut the pool down properly — shutdown() + awaitTermination() or try-with-resources (Java 19+) — and make sure the program ends on its own.

Expected output (the numbers are an example):

Main.java: 42
Utils.java: 17
missing.txt: error - NoSuchFileException
Total lines: 59, files read: 2 of 3

Where the exception goes

An exception from call() does not reach main by itself: get() throws ExecutionException, and the original NoSuchFileException is in getCause(). If you never call get(), the error disappears silently (see execute() vs submit()). A harder variant: do the same for a list of URLs with HttpClient and get(2, TimeUnit.SECONDS).

At Most Two Connections: Semaphore with a Timeout

The “database” has only two connections, and 8 clients want to use it at the same time. Limit access with a Semaphore.

  1. Create a Semaphore with 2 permits.
  2. Each client is a separate thread. It tries to get a permit with tryAcquire(1, TimeUnit.SECONDS). If it succeeds, it prints “Client N: connected”, “works” for 500 ms and releases the permit. If it does not get one within a second, it prints “Client N: rejected on timeout”.
  3. Count the clients working at the same time in an AtomicInteger and remember the maximum.
  4. At the end, print how many clients were served, how many were rejected and the maximum number of simultaneous connections.

Expected output: there are never more than 2 simultaneous connections. Usually 4–6 clients are served and the rest are rejected: within one second of waiting, permits are freed for only two “waves” of clients. The exact numbers depend on the scheduler.

Common mistake

release() belongs in finally, and only if the permit was actually acquired. A semaphore has no owner: an extra release() after a failed tryAcquire() silently increases the number of permits, and three clients get connected (see a Semaphore has no owner).

Start When the Services Are Ready: CountDownLatch

The application must start accepting requests only when three services are ready: the cache, the database and the message queue.

  1. Each service starts in its own thread and takes a different time to “start”: 300, 700 and 1200 ms.
  2. Create a CountDownLatch with a count of 3. After starting, each service writes its state (READY or FAILED) to a shared ConcurrentHashMap and calls countDown().
  3. The main thread waits for the services with await(1, TimeUnit.SECONDS). If all of them are ready in time and none has failed, it prints “Application started”. Otherwise it lists the problem services and prints “Startup cancelled”.
  4. Make one of the services fail with an exception during startup. The program must still not wait longer than the timeout.

Expected output: with delays of 300/700/1200 ms, only two services are ready within a second — “Not ready: message queue”, “Startup cancelled”. Reduce the third delay to 900 ms, and the application starts. main sees the failed service in the map as FAILED and cancels the startup.

Hint

Call countDown() in finally: if a service fails before that line, the count never reaches zero, and await() without a timeout hangs forever. await(time, unit) returns false if the time ran out — use that value to decide what to print (see CountDownLatch).

10,000 Requests: Virtual Threads vs a Thread Pool

Compare how a pool of platform threads and virtual threads cope with a large number of blocking tasks. You need Java 21 or newer.

  1. A “request” task simulates waiting for a network response: Thread.sleep(100), then it increments a shared AtomicInteger.
  2. Submit 10,000 such tasks to Executors.newFixedThreadPool(100) and measure the time until all of them finish.
  3. Repeat with Executors.newVirtualThreadPerTaskExecutor(). Close both executors with try-with-resources: close() waits for all tasks.
  4. For each variant, print the time and the counter value.
  5. Replace sleep() with a computation (for example, the sum of the squares of the numbers up to 1,000,000 in a loop) and compare again.

Expected output: the pool of 100 threads takes at least 10 seconds — 10,000 tasks go through in 100 “waves” of 100 ms. Virtual threads finish in a fraction of a second. The counter is 10,000 in both cases. With computations the gain disappears: the number of cores is the same, and a virtual thread does not compute faster than a platform thread.

A subtle point

Virtual threads are not put into a fixed-size pool: you create one per task. If you need to limit the number of simultaneous requests to an external service, use a Semaphore, not the pool size. Why computations do not speed up is explained in virtual threads and CPU-bound work.

Producer-Consumer on a BlockingQueue with a Poison Pill

Rewrite the data exchange between a producer and consumers without wait()/notify(), on a ready-made blocking queue.

  1. The producer creates 50 orders (objects with a number) and puts them into an ArrayBlockingQueue with a capacity of 10 using put().
  2. Three consumers take orders with take(), “process” each one for 20–50 ms and print who processed which order.
  3. When the producer is done, the consumers must finish on their own. Use a poison pill — a special marker order: a consumer that gets it leaves the loop.
  4. At the end, each consumer prints how many orders it processed. main waits for all of them with join() and prints the total.

Expected output: the orders are distributed among the consumers unevenly and differently every time, but the total is always 50, and the program ends without System.exit().

Hint

You need as many pills as there are consumers: one pill stops only the consumer that took it, and the others stay stuck in take(). Put the pills in after the last real order. A breakdown with several producers is in the section Multiple Producers and Consumers: the Poison Pill; compare this solution with your MyQueue from the exercise above.

Money Transfers Without a Deadlock: ReentrantLock and tryLock

A bank has 5 accounts with 1000 on each. Four threads at the same time make 10,000 transfers each, of a random amount between random accounts.

  1. Each account has its own ReentrantLock. A transfer holds the locks of both accounts, so that the debit and the credit happen together.
  2. First write the naive version: from.lock.lock(), then to.lock.lock(). Make sure the program hangs sooner or later.
  3. Fix it with tryLock(): wait for the first lock with a timeout, take the second one without waiting; if that fails, release the first one, pause for a short random time and try again.
  4. Reject a transfer when the balance is too low instead of taking the account below zero. Skip transfers to the same account.
  5. At the end, print the balances, their sum and the number of retries.

Expected output: the sum of the balances is always 5000, and the fixed program always finishes. The number of retries changes from run to run.

Alternative

The second way is to always acquire the locks in the same order, for example by ascending account number: then there is no circular waiting and no retries are needed. Call unlock() in finally and only for the locks you managed to acquire. tryLock() is covered in the section tryLock(), the conditions of a deadlock in the lesson Deadlock in Java.

An Async Pipeline with CompletableFuture: Load, Process, Save

Collect data from three sources asynchronously, without blocking threads while waiting for each step.

  1. The load(String source) method simulates loading: a pause of 200–800 ms and a list of strings. Source C throws an IllegalStateException.
  2. For each source, build a chain: supplyAsync(() -> load(source), executor) → thenApply (keep non-empty strings and convert them to upper case) → thenCompose with an asynchronous save() that returns a CompletableFuture<Integer> — the number of saved records.
  3. Handle a source error inside its own chain (exceptionally or handle): print a message and return 0, so that the other sources are not affected.
  4. Combine the three chains with CompletableFuture.allOf() and print the total number of saved records.
  5. Limit the whole operation in time with orTimeout(2, TimeUnit.SECONDS) and test it by raising the pause of one source to 3 seconds.
  6. Use your own thread pool for the tasks and close it at the end.

Expected output (the order of the lines depends on the pauses):

A: saved 3
C: error - IllegalStateException: source unavailable
B: saved 5
Total saved: 8, sources with errors: 1

When the timeout is exceeded, join() throws a CompletionException whose cause is a TimeoutException.

Where people usually go wrong

In exceptionally after supplyAsync, you get a CompletionException, not the original exception; the real cause is in getCause(). Using thenApply instead of thenCompose for the asynchronous save() gives the type CompletableFuture<CompletableFuture<Integer>>. And orTimeout() completes the future but does not stop the task itself (see exception handling and timeouts).

Find a Deadlock in a Running Program and Fix It

A practical interview task: “the program hangs — find the cause”.

  1. Write a program in which thread 1 locks monitor A, then B, and thread 2 locks B, then A. Put a 100 ms pause between the two locks so that the deadlock happens on every run.
  2. Without stopping the program, take a thread dump: jcmd <pid> Thread.print or jstack <pid> (jcmd without arguments shows the pid). Find the deadlock section in the dump and work out which thread holds which monitor and which one it is waiting for.
  3. Add a “watchdog” daemon thread that calls ManagementFactory.getThreadMXBean().findDeadlockedThreads() once a second and, when it finds a deadlock, prints the names of the deadlocked threads.
  4. Fix the program without removing either of the two monitors.

Expected output: the dump contains the line Found one Java-level deadlock:, and both threads are BLOCKED. The watchdog prints the names of the two threads about a second after the start. After the fix, the program finishes.

Hint

findDeadlockedThreads() returns null when there is no deadlock — check for that before iterating over the array. The fix is one lock order for the monitors in both threads. How to read a dump is shown in How to Detect a Deadlock.

Even and Odd Numbers in Turn in Two Threads

One of the most common practical interview tasks: two threads print the numbers from 1 to 20 strictly in turn — the odd thread prints the odd numbers, the even thread prints the even ones.

  1. Solve it with wait()/notify(): a shared monitor object and a field that says whose turn it is.
  2. Solve the same task with two Semaphore objects: odd starts with one permit, even with zero; after printing a number, a thread hands a permit to the other one.
  3. Both programs must end on their own, without System.exit().

Expected output, always the same:

odd: 1
even: 2
odd: 3
...
even: 20

Typical slip

Check the “is it my turn?” condition in a while loop around wait(), not in an if, and do not forget the last notify(): otherwise one of the threads stays waiting forever after the number 20. A solution based on Thread.sleep() instead of synchronization does not count: it does not guarantee the order (see wait() in a loop).

Your Own Thread Pool on a BlockingQueue

Interviewers ask you to “write a simple thread pool” to check whether you understand what happens inside an ExecutorService.

  1. The SimpleThreadPool class takes the number of worker threads in its constructor and creates them with the names worker-1, worker-2…
  2. The execute(Runnable task) method puts the task into a BlockingQueue<Runnable>; the worker threads take tasks from the queue in a loop and run them.
  3. An exception inside a task must not kill the worker thread: catch RuntimeException, print it and go on.
  4. The shutdown() method: new tasks are no longer accepted (execute() throws RejectedExecutionException), the tasks already in the queue are run, and then the worker threads finish.
  5. The awaitTermination() method waits until all worker threads have finished.
  6. Test the pool: 3 worker threads, 20 tasks of 100 ms each, one of the tasks throws an exception.

Expected output: only worker-1…worker-3 run the tasks; 19 tasks print their result, one prints an error message. The total time is about 700 ms (20 tasks of 100 ms on three threads). Calling execute() after shutdown() throws RejectedExecutionException, and after awaitTermination() the program ends.

Hint

There are two ways to stop the worker threads: put one poison pill per thread into the queue, or set a flag and interrupt the threads with interrupt(). In the second case, do not lose the tasks still waiting in the queue. How this works in the JDK is shown in ThreadPoolExecutor.

When you write the programs, follow the code style checklist.

How to Check a Multithreaded Solution

One successful run proves nothing: races and deadlocks do not show up every time. You check a multithreaded solution with a series of runs under load, with invariants verified after all threads have finished, and with a thread dump if the program hangs.

Run the program 10–20 times in a row and raise the load: a million iterations instead of a thousand, eight threads instead of two. A race you never see at a thousand iterations usually shows up at once at a million.

Check the result only after join(), await() or close() of the pool. If main just sleeps for a second and then prints the counter, you are testing the speed of your computer, not your program. Invariants that do not depend on the order of execution work well: the sum of balances does not change after transfers, the number of processed orders equals the number of created ones, the sum of word frequencies equals the number of words.

If the program hangs, do not restart it right away. Run jcmd without arguments, find the pid of your program and take a dump with jcmd <pid> Thread.print. The dump shows which thread is in which state (BLOCKED, WAITING) and what it is waiting for, and a deadlock on monitors is detected by the JVM itself: it prints Found one Java-level deadlock.

In practice solutions, give every wait a timeout — join(5000), await(5, TimeUnit.SECONDS), awaitTermination(5, TimeUnit.SECONDS) — and print a message when the time runs out. Instead of a silently hanging console, you will see at which step the program gave up waiting.

Frequently Asked Questions

What multithreading tasks are asked in Java interviews?

Most often you are asked to print numbers from two threads in turn, write a producer-consumer, reproduce and fix a deadlock, build a thread-safe counter and explain the difference between synchronized, volatile and AtomicInteger. For middle and senior positions, interviewers add a simple thread pool or an async pipeline on CompletableFuture. All of them are on this page: even and odd numbers in turn, Producer–Consumer, finding a deadlock, your own thread pool.

Which exercise should I start with if multithreading feels hard?

With the first three, in order: a thread via Thread, threads via Runnable, a letter printed in three threads with synchronized. Then solve “Wait for Several Threads” and “A Counter Without Lost Updates”: they show clearly how threads behave without synchronization. Move on to the ExecutorService, CompletableFuture and ReentrantLock exercises when these five work out without hints.

Why practice with Thread if real projects use ExecutorService?

In production code you rarely create threads by hand: tasks go to a pool or into a CompletableFuture. But a pool runs tasks on the same kind of threads, and races, visibility problems and deadlocks are exactly the same there. With threads you create yourself, it is easier to see where these problems come from, and then the same techniques carry over to a pool — as in the exercise on counting lines in files.

Which Java version do I need for these exercises?

Most exercises run on Java 8. orTimeout() in CompletableFuture appeared in Java 9, closing an ExecutorService with try-with-resources in Java 19, and newVirtualThreadPerTaskExecutor() in Java 21. On Java 17, replace try-with-resources with shutdown() and awaitTermination() and leave the virtual threads exercise until you upgrade. On a current LTS release, Java 21 or 25, all 21 exercises run as written.

Comments

Please log in or register to have a possibility to add comment.