How to use Confluence's ThreadLocalCache class

I have a question on a Confluence com.atlassian.confluence.cache.ThreadLocalCache class that we’re using in our apps and that is also relevant for other vendors when they’re making their apps compatible with ours.

The class javadoc contains this:

The most important rule for this cache is use custom types for keys. If you use some generic key type like a String, you will inevitably clobber someone else’s cached data.

I read the code multiple times and I simply cannot understand why this would be true. It seems this is just wrong. We’ve also been ignoring this warning and simply used unique and namespaced string values as keys, which has worked well in the last couple of years.

I’m bringing this up here now because I’m about to recommend that class to another vendor for compatibility improvements with our apps and since that Javadoc comment might confuse them I just wanted to double check if my understanding is correct.

Thanks!

2 Likes

Hi @jens,

I read the code multiple times and I simply cannot understand why this would be true. It seems this is just wrong.

Above is a generic recommendation and holds mostly true. Since ThreadLocalCache is dedicated to a Thread, consider the scenario where Confluence’s web request goes through multiple ServletFilters, Servlets for a targeted endpoint. These Filters/Servlets can mistakenly use have identical Strings for cache keys that can cause inconsistent behaviour. Hence, we recommend finding a unique key(class with hashcode/equals implemented) for a Cached item.
It also provides foolproof and simplistic way of making sure keys are unique and are not overwritten by other plugins.

Of course, if you will still use String with your plugin’s fully qualified name as a prefix, it will have near to zero chance, some other plugin can mess that cache up. I don’t see a major issue with this approach.
Still, as a recommendation, having a Key class(with simple hashcode() and equals()) provides simplicity and a better control in hashed gets.

Thanks

1 Like