How to achieve concurrency in Scala without using Futures or Akka?
Instruction: Discuss alternative approaches to achieve concurrency in Scala, excluding Futures and Akka.
Updated
Concurrency means computations can make progress during overlapping periods; parallelism means they actually execute at the same time. Scala on the JVM can use Java threads and concurrency primitives without Scala Future or Akka.
import java.util.concurrent.atomic.AtomicInteger
@main def threadsExample(): Unit = {
val count = new AtomicInteger(0)
val workers = Vector.fill(2)(new Thread(new Runnable {
def run(): Unit = {
var i = 0
while (i < 1000) {
count.incrementAndGet()
i += 1
}
}
}))
workers.foreach(_.start())
workers.foreach(_.join())
assert(count.get() == 2000)
}
The atomic increment prevents lost updates. join blocks the caller until each worker terminates; this is a small concurrency demonstration, not a nonblocking API. Calling run directly would execute on the caller's thread. A shared plain var with += 1 would not provide the atomicity required here. AtomicInteger, Thread lifecycle
For larger workloads, use managed executors with bounded admission and an explicit shutdown policy, or an effect runtime with owned fibers, cancellation and resource handling. Worker exceptions must be reported explicitly; join does not rethrow a worker's failure. Define how interruption, deadlines and cleanup work rather than leaving background work unowned.
On JDK 21 and later, virtual threads offer lightweight JVM threads for suitable blocking I/O workloads. They do not make CPU work faster, remove shared-state races, or remove limits on database connections and remote services. Do not pool virtual threads merely to limit their count; limit access to the constrained resource. The example above uses platform threads and runs on JDK 17. Virtual-thread guidance
Software transactional memory is a shared-state coordination technique, not an execution scheduler or a durable database transaction. Its retried transaction bodies must not freely repeat external side effects.