Thread freezes on initialising an object in scala referencing the object being initialised

时间:2018-03-23 00:46:39

标签: multithreading scala object initialization

I struggled with a specific problem with java Threads and initialisation of an object in scala. In my original code a Thread freezes. I finally found a solution for my problem. But I do not understand why this works.

I have rewritten the problem into the following code. Running this, the code stops at the first line in the Thread that references to a variable of the object being initialised. If the reference is through the self variable which points to this initialising object, it executes fine.

object Alpha {
    var r = "A"
    r = "B"
    System.out.println("Not threaded: r = " + r)
    val thread = 
        {
            val self = this

            new Thread(
                new Runnable 
                {
                    def run() =
                        {
                            System.out.println("    Started.")
                            System.out.println("    Threaded self.r = " + self.r)
                            self.r = "C"
                            System.out.println("    Threaded self.r = " + self.r)

                            // At the following line the thread freezes!
                            System.out.println("    Threaded r = " + r) 
                            r = "D"
                            System.out.println("    Threaded r = " + r)
                        }
                })
        }
    thread.start
    thread.join
}

Calling Alpha will result in the following output before execution is frozen.

Not threaded: r = B
    Started.
    Threaded self.r = B
    Threaded self.r = C

I would understand if referencing to object variables during initialisation is prohibited at all times. But now it looks a bit randomly.

0 个答案:

没有答案