Threads
Java threads, executors and futures, with Ring functions that run while the program waits.
What you will learn#
new Threadwith a Ring function, andjJoin,- an
ExecutorService,CallableandFuture, - atomic values,
jWaitUntilto wait while callbacks are served.
The program#
# Tutorial 9: threads - Java threads, executors and the Ring program that serves their callbacks
load "java.ring"
using {
"java.lang"
"java.util.concurrent"
"java.util.concurrent.atomic"
}
Executors = new Executors
TimeUnit = new TimeUnit
# 1. a Java thread that runs a Ring function; jJoin waits for it and runs its callbacks
nCounter = 0
oThread = new Thread(jCallback("count"))
oThread.start()
jJoin(oThread)
? "counter after the thread: " + nCounter
# 2. a pool of threads and a Callable: submit gives a Future
oPool = Executors.newFixedThreadPool(2)
oFuture = oPool.submit("compute")
jWaitUntil("futureDone",5000) # get() would block the Ring program, which has to run the callback: wait with jWaitUntil first
? "future: " + oFuture.@get()
# 3. several tasks: each one is a Ring function that runs while the Ring program waits
aFutures = []
for nTask = 1 to 4
aFutures + oPool.submit("square")
next
jWaitUntil("allDone",5000)
nSum = 0
for oOne in aFutures
nSum += oOne.@get()
next
? "sum of four results: " + nSum
# 4. shut the pool down and wait
oPool.shutdown()
oPool.awaitTermination(5,TimeUnit.SECONDS)
? "pool finished: " + oPool.isTerminated()
# 5. atomic values are safe between threads
oAtomic = new AtomicInteger(0)
oAtomic.addAndGet(5)
oAtomic.incrementAndGet()
? oAtomic.@get()
# 6. wait for a condition while the callbacks are served
lDone = false
oLater = new Thread(jCallback("finish"))
oLater.start()
jWaitUntil("isFinished",5000)
? "the other thread finished"
func futureDone
return oFuture.isDone()
func allDone
for oOne in aFutures
if oOne.isDone() = 0
return false
ok
next
return true
func count aArgs
for nI = 1 to 3
nCounter++
next
func isFinished
return lDone
func compute aArgs
return 6 * 7
func square aArgs
return 5 * 5
func finish aArgs
lDone = truecounter after the thread: 3
future: 42
sum of four results: 100
pool finished: 1
6
the other thread finishedHow it works#
The Ring program is single-threaded: Ring functions called by other Java threads are queued and run on the Ring thread when the program waits (jJoin, jWaitUntil or jMainLoop). A get() on a future would block the program that has to run the callback, so the lesson waits with jWaitUntil. That means no data of the program is shared between two threads at once. Values shared with pure Java threads (counters) use atomic classes.
Exercises#
- Run five tasks in a pool of two threads and print which finishes first.
- Add 1000 to an
AtomicIntegerfrom four threads. - Wait until a flag is set with
jWaitUntil.