Fix terrible bug

The cache thread could exit unexpectedly. Refactored the code so that
its behaviour is type checked.