Fix #138 and #116. Simplify some synchronization logic. Fix junit.