do Closures close over Sychronized monitor blocks?...
# announcements
b
do Closures close over Sychronized monitor blocks? I declare a
FixedThreadPool
executor within a synchronized block, and I pass in a ThreadFactory Lambda fun; when the threadfactory function is subsequently evaluated, will the Monitor lock be acquired? (I am hoping/expecting not - otherwise I would put the sychronized inside the ThreadFactory fn)
but I had a nasty thought that it might...
c
Do you have any example code?
b
something like this illustrates it
Copy code
var myExec: ExecutorService? = null

fun createOrReturnMyExec() {
    synchronized(this) {
        if ((myExec == null) || (myExec!!.isShutdown)) {
            myExec = Executors.newFixedThreadPool(10) {runnable ->
                /*
                 * Is this going to have the synchronized(this) monitor acquired when it finally gets run?
                 * (I hope not)
                 */
                Thread(runnable)
            }
        }
    }
}
obvs that code is simplified to the point where it is not useful, other than to illustrate the point
c
So that code will create a fixed ThreadPoolExecutor. The underlying implementation creates threads as they are required using the underlying thread factory. This happens outside the scope of the synchronized block, so no you will not have hold of the monitor when the thread is created. This is really a Java question though, because if the implementation happened to synchronously create the 10 threads during the creation of the executor, the monitor would have been held. Basically, anything happening between the start and the end of the synchronized block will happen with the monitor held.
👍 1
b
thanks
yeah so Monitors do not get captured as part of a closure
cool
c
Also, there’s a good chance you don’t actually want to be reaching for synchronized. It’s quite expensive and you have to consider deadlocks, especially when you can use non-blocking primitives like AtomicReferences, constructor injection, volatiles, and the like.
b
well thats a seperate issue
👍 1
actually I've got coroutines to juggle, and I just realised the
synchronised
is very much less helpful than I'd hoped - all it means is the coroutine all interleave themselves on the same Monitor-owning thread
so that'll teach me