Implemented refcounting for Messages

Fixes to locking implementation
Eliminated memory leaks