Rewrote locking such that it does not lock when running foreign code.