smallrye-metrics icon indicating copy to clipboard operation
smallrye-metrics copied to clipboard

MemberToMetricMappings should be thread-safe

Open mkouba opened this issue 3 years ago • 5 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()).

mkouba avatar Aug 03 '21 14:08 mkouba

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?

jmartisk avatar Aug 04 '21 10:08 jmartisk

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.

mkouba avatar Aug 04 '21 11:08 mkouba

Better be safe than sorry ;-)

mkouba avatar Aug 04 '21 11:08 mkouba

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.

jmartisk avatar Aug 04 '21 11:08 jmartisk

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 ;-).

mkouba avatar Aug 04 '21 11:08 mkouba