Thread safe changes

Forward port of #1292.