synchronized Scala and Java versions of problem #2