Skip to content

Synchronization

Keith Alcock edited this page Apr 3, 2021 · 4 revisions

FatDynet is intended to be thread safe if not (and soon to be) multi-threaded. Still, now and in the future, there are a few parts that need to remain synchronized, particularly initialization. These parts can be managed by the Synchronizer. It's not completely automatic and there are several ways you can run amok. It will complain by throwing a SynchronizationException when you do, but that's little consolation after your program has run for days. The main thing to remember is that synchronization in Java/Scala only guards against two different threads entering the critical section at the same time. The same thread is welcome back into the section, as the thread would otherwise be deadlocked. Here are some things to watch out for in that regard. They are demonstrated in TestSynchronization code.

  • A Scala lazy val can be initialized long after you've forgotten about it. If its initialization requires synchronization and it happens to be referenced for the first time from synchronized code, the critical section will be entered twice and the Synchronizer will complain.
  • Scala companion objects are not usually initialized until they are referenced. They might be thought of as lazy classes. If their initialization requires synchronization and this happens in some round about way while something else is being synchronized, you will also get complaints.
  • Exception handlers within synchronized sections should not call synchronized code themselves. The possibility might not be obvious because Scala doesn't mark methods for the exceptions they throw and also because the exception might be thrown far away from where it's caught.