fix index out of bounds and thread safety