added synchronized statements to make the code threadsafe without
sacrificing performance too much.