smallrye / smallrye-metrics

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

MemberToMetricMappings should be thread-safe

mkouba opened this issue · comments

Because it can be used from multiple threads.io.smallrye.metrics.MemberToMetricMappings.counters and others should be final and ConcurrentMap. The same applies to the values - these should be synchronized as well (e.g. via CopyOnWriteArraySet or Collections.synchronizedSet()).

Do we actually use it from multiple threads (for modification) somewhere? Because populating this map is a thing that happens at build time (startup time in JVM) by iterating through available annotations. I think neither Quarkus nor the portable CDI extension (which is used in WildFly) use multiple threads for this, am I mistaken?

Do we actually use it from multiple threads (for modification) somewhere?

Well, the question is whether it can be used from multiple threads... Another point is that those structures do not ensure safe propagation, i.e. the changes may not be visible from other threads.

Better be safe than sorry ;-)

If we don't plan modifying this in multiple threads, then synchronizing comes with an unnecessary performance penalty, in which case I think we should just make it more clear (in Javadoc) that modifying in multiple threads is forbidden?!
I'm not sure if we can hit the "changes not visible from other threads" problem, I assume that HashMap and HashSet should prevent that as long as there aren't multiple "writing" threads. The javadoc of HashMap says

If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

(And similarly for HashSet). So with one writing thread and later multiple reading threads we should be fine I think.

No objection to making the fields final, that can't hurt anything.

If we don't plan modifying this in multiple threads, then synchronizing comes with an unnecessary performance penalty, in which case I think we should just make it more clear (in Javadoc) that modifying in multiple threads is forbidden?!

I think that this penalty would be negligible but it's ok to clarify the contract in the javadoc too.

It might make also sense to optimize the structures after the mappings are intialized, e.g. use some immutable structures.

And speaking of performance - the interceptors could reuse a CDIMemberInfoAdapter instance instead of creating a new one for each interception ;-).