moved the lock in the Next function to mimic the synchronized block in the original Scala code