Threadsafe cache shrinkage

This PR fixes #557. The name of the regression test is a bit long, but as test functions are never called within the code I'm fine with that. Though, if anyone comes up with a shorter name, feel free to change it.

Also reduced code duplication in the test as almost all where creating the same test data which is done in a separate function now.