Implement reference counting in keyvalue
In the case where one thread frees a keyvalue object while another thread contains an already-fetch reference, this would lead to UAF. Use an atomic and mutex-protected reference counter. Only free the object when the count reaches 0.