Fix issue 597 -- entity manager is properly removed even if close operation fails + unit test.

The issue is critical because once the em wasn't removed, the thread (typically a pool thread) is lost forever. Every "start" operation would fail with this thread ...