Fix thread safety issue and possible NPE

Thanks to @kitskub