Threads: Java and C++

A thread in Java is an object with a start and a join; a thread in C++ is an object with a std::thread constructor and a join that must be called or the program terminates. Both run a function on another stack and both share the heap. The difference that matters is what the language promises when two threads touch the same variable: Java defines the result, and C++ does not.

The task

Three workers that each compute a sum and write it into their own slot of an array, joined before the reads, and then two threads that increment one shared counter fifty thousand times each through a synchronized method. The first half has no shared write, the second has one, and both are exact on every run.

The Java version

import java.util.ArrayList; import java.util.List; public class Sums { static class Counter { private long value; synchronized void increment() { value++; } synchronized long value() { return value; } } public static void main(String[] args) throws InterruptedException { int[] parts = new int[3]; List<Thread> workers = new ArrayList<>(); for (int i = 0; i < 3; i++) { int part = i; Thread worker = new Thread(() -> { int sum = 0; for (int n = 1; n <= (part + 1) * 100; n++) { sum += n; } parts[part] = sum; }, "sum-" + (i + 1)); workers.add(worker); worker.start(); } for (Thread worker : workers) { worker.join(); } int total = 0; for (int i = 0; i < parts.length; i++) { System.out.println("part " + (i + 1) + ": " + parts[i]); total += parts[i]; } System.out.println("total: " + total); Counter counter = new Counter(); Thread a = new Thread(() -> { for (int i = 0; i < 50_000; i++) { counter.increment(); } }); Thread b = new Thread(() -> { for (int i = 0; i < 50_000; i++) { counter.increment(); } }); a.start(); b.start(); a.join(); b.join(); System.out.println("counter: " + counter.value()); System.out.println("exact: " + (counter.value() == 100_000)); } }

javac -Xlint:all -d out Sums.java
java -cp out Sums

part 1: 5050
part 2: 20100
part 3: 45150
total: 70300
counter: 100000
exact: true

The parts are the sums of 1 to 100, 1 to 200 and 1 to 300, and the output is the same on every run because the workers write different slots and the joins order the reads. The counter is exact because both methods are synchronized: the monitor makes the read, the add and the write one step, and the second method is synchronized so that the read at the end sees the writes.

The Java memory model

Java has a written rule for what a thread may see, and it is called the Java memory model. A write by one thread is guaranteed to be seen by another only through a synchronisation point: a monitor, a volatile field, an atomic variable, a thread start or a join. The model allows the compiler and the processor to reorder and cache within those rules, and a program that shares a plain field without one has a data race that the model defines as a program that may see either value.

C++ has a model too, and it says the opposite about the same program: a data race is undefined behaviour, not a choice between two values. The C++ atomics and mutexes are the same tools with different names, and the memory orders are the same idea; the difference is the consequence of getting it wrong, which the last page of this group is about.

The C++ version

The C++ program has the same shape and one obligatorily different detail: every std::thread is joined, because a thread object that is destroyed while joinable calls std::terminate. The block is not compiled here, because the image has no g++.

#include <iostream> #include <mutex> #include <thread> #include <vector> class Counter { public: void increment() { std::lock_guard<std::mutex> lock(mutex_); ++value_; } long value() { std::lock_guard<std::mutex> lock(mutex_); return value_; } private: std::mutex mutex_; long value_ = 0; }; int main() { Counter counter; std::vector<std::thread> workers; for (int i = 0; i < 2; ++i) { workers.emplace_back([&counter] { for (int n = 0; n < 50'000; ++n) { counter.increment(); } }); } for (std::thread& worker : workers) { worker.join(); } std::cout << "counter: " << counter.value() << '\n'; }

The C++ program would print counter: 100000. The mutex and the lock guard are the monitor and the synchronized block, and the join is the join. The one line that has no Java counterpart is the destructor of std::thread: it runs after the last use, and a program that forgets a join or a detach does not leak a thread, it aborts.

What differs and why

Java threads are objects that a program creates and forgets: a running non-daemon thread keeps the JVM alive, and the main thread may finish while the others run. C++ threads are values that must be joined or detached before they are destroyed, and the rule is enforced by std::terminate at run time. A Java program that starts a thread and returns is a normal shape; the same C++ program does not compile without a decision.

The shared state has the same tools under different names. A Java monitor is a mutex plus a condition, a synchronized method is a lock guard around one call, and AtomicLong is std::atomic<long>. The Java memory model defines the visibility rules for all of them, and the C++ memory model does the same with memory orders that a Java program cannot state.

The cost is the same on both sides. A contended lock parks the thread, a volatile read costs a barrier, and an atomic increment is a compare-and-swap loop. The difference that shows up in production is the failure mode: a Java race gives a wrong number, and a C++ race gives a wrong number or a crash or nothing, depending on the optimiser.

The habit that breaks

The habit is to assume that the order of the statements is the order the machine sees. A C++ programmer knows that the optimiser may keep a value in a register, and writes the same Java loop with a plain field and expects it to stop. It compiles, and the JVM is allowed to hoist the read: the loop may never see the other thread's write. The fix is the same word as in C++, a volatile field or a lock, and the lesson is that both languages give the compiler the same freedom.

The second habit is to share a mutable object between threads because the reference is final. final stops the reference from changing and says nothing about the fields of the object; the object is safe to share only if it is immutable or if every access is synchronized. The concurrency part of the Java course, from lesson 114 to lesson 123, is the long form of this page.

The next page

The last page is undefined behaviour: the bounds check that Java performs and C++ does not, the null check, and the program that reads past an array in one language and throws in the other. The C++ lesson is threads, and the Java lesson is threads.

The Java program was compiled with OpenJDK 21.0.13 (javac) and run on Alpine Linux in a Docker container. The C++ program is shown and was not compiled here: the image has no g++.

Article author: Arthur Isaev