This uses atomics to lock out concurrenct writes/reads, and fixes some potential null pointer dereferences.