Thread safety changes

Let me know if you have any questions about these changes.