The 30 second answer
The task is to compute order count, total and maximum price over a million orders with four threads. The Java version shares one stats object, so every add is synchronized and all four threads compete for one lock. The Scala version gives each worker its own chunk and its own immutable result, then merges four results at the end. There is no lock and no shared write. Both print the same numbers.
The task. There are 1,000,000 orders, priced 1 to 100 cents in a repeating pattern. Compute the count, the total and the maximum with four parallel workers. Both programs print a count of 1,000,000, a total of 50,500,000 and a max of 100.
Java: shared mutable state plus a lock.
public class StatsJava {
// One shared, mutable object: every thread writes into it, so every write must be locked.
static class OrderStats {
private long count;
private long totalCents;
private long maxCents;
synchronized void add(long cents) {
count++;
totalCents += cents;
if (cents > maxCents) maxCents = cents;
}
synchronized String report() {
return "count=" + count + " total=" + totalCents + " max=" + maxCents;
}
}
public static void main(String[] args) throws InterruptedException {
long[] orders = new long[1_000_000];
for (int i = 0; i < orders.length; i++) orders[i] = i % 100 + 1;
OrderStats stats = new OrderStats();
Thread[] workers = new Thread[4];
int chunk = orders.length / workers.length;
for (int w = 0; w < workers.length; w++) {
int from = w * chunk;
int to = from + chunk;
workers[w] = new Thread(() -> {
for (int i = from; i < to; i++) stats.add(orders[i]); // 4 threads compete for one lock
});
workers[w].start();
}
for (Thread t : workers) t.join();
System.out.println(stats.report()); // count=1000000 total=50500000 max=100
}
}Scala: immutable values, split, then merge.
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.*
// An immutable value: "changing" it returns a new Stats and leaves the old one untouched.
final case class Stats(count: Long, totalCents: Long, maxCents: Long):
def add(cents: Long): Stats =
Stats(count + 1, totalCents + cents, math.max(maxCents, cents))
def merge(other: Stats): Stats =
Stats(count + other.count, totalCents + other.totalCents, math.max(maxCents, other.maxCents))
object Stats:
val empty = Stats(0, 0, 0)
@main def runStats(): Unit =
val orders = Vector.tabulate(1_000_000)(i => (i % 100 + 1).toLong)
val chunks = orders.grouped(250_000).toVector
// Each worker folds its own chunk into its own Stats: nothing is shared, so nothing is locked.
val partials = chunks.map(chunk => Future(chunk.foldLeft(Stats.empty)(_.add(_))))
val total = Await.result(Future.sequence(partials), 10.seconds).foldLeft(Stats.empty)(_.merge(_))
println(total) // Stats(1000000,50500000,100)Verified with OpenJDK 21.0.13 and Scala 3.3.4: both print the same count, total and maximum.
What a beginner should notice.
- Who owns the data. In Java, one object is owned by everyone, so it needs a lock. In Scala, each worker owns its chunk and its result, so it needs none.
- What "add" means. Java's
addchanges the object. Scala'saddreturns a newStats, which is whyfoldLeftcan thread it through a loop. - The merge step. Because
mergeis a pure function that is associative, the partial results can be combined in any grouping. That is the same idea behind map-reduce and Elasticsearch aggregations, where each shard computes a partial result and the coordinating node merges them. - You can write the Scala style in Java. A Java record with
addandmergemethods that return new records, plus one task per chunk, gives the same lock-free design. The language makes it the default, not the only option.
Sources (2)
- Scala 3 book: Pure functionsdocs.scala-lang.org
- Oracle Java tutorial: Immutable objectsdocs.oracle.com