Code cleanup, and thread safety

The main impetus behind this was to make the MetadataCache thread-safe. Along the way, I made some other minor  code-quality adjustments.