Thread-safety and ugly performance tweaks