I have a `private val done:MutableSet<T> = m...
# announcements
s
I have a
private val done:MutableSet<T> = mutableSetOf()
in a class. Method
a
starts a thread which calls method
b
, which has
synchronized(done)
. I intermittently get an NPE on
synchronize(done)
. I moved the
private val done
declaration from between
a
and
b
to above
a
and that seems to have fixed it. Am I crazy?
z
So this NPEs:
Copy code
fun a() = thread { synchronized(done) { … } }
private val done = …
fun b() = …
But this doesn't:
Copy code
private val done = …
fun a() = thread { synchronized(done) { … } }
fun b() = …
Where/when are you calling a?
s
More like this. a is called from init(), which I suspect is integral to the problem.
So far it only fails intermittently, and only on my CI system, never on my laptop.
z
Ah yes, that's an important detail 😉 Accessing members from constructors is a great source of bugs. And I was wondering about intermittent failures too - this looks like it's a race condition, it probably doesn't matter what order you define a relative to done, because your init block is before your done initialization, the thread will always get started before done is initialized. Whether the code in the thread actually makes it to your synchronized call before done is initialized is up to the OS.
I think moving your property declarations above your init block should fix this (and, at least imo, generally makes classes easier to read).