Add thread id to key and some refactoring