Fix a bug in lockAndSwapMem and some refactors