Skip to content

MT-safety of HistoOnEvent example #647

@magicwerk

Description

@magicwerk

I use

https://github.com/btraceio/btrace/blob/master/btrace-dist/src/main/resources/samples/HistoOnEvent.java

as base for collecting information for classes.

	public static void onnewObject(@Self Object obj) {
        String cn = name(classOf(obj));
        AtomicInteger ai = get(histo, cn);
        if (ai == null) {
            ai = newAtomicInteger(1);
            put(histo, cn, ai);
        } else {
            incrementAndGet(ai);
        }
    }

However I have the problem that the results are not accurate due to MT issues.
If I add log statements, I get the following output:

start of onnewObject for Thread[Thread-6,5,main]
newAtomicInteger org.apache.commons.lang3.builder.EqualsBuilder

start Thread[Thread-7,5,main]
newAtomicInteger org.apache.commons.lang3.builder.EqualsBuilder

end of onnewObject for Thread[Thread-7,5,main]

end of onnewObject for Thread[Thread-6,5,main]

Obviously access to onnewObject is not synchronized by BTrace itself and I cannot add synchronized myself because it's prohibited.

The statements

        AtomicInteger ai = get(histo, cn);
        if (ai == null) {
            ai = newAtomicInteger(1);

use check-then-act which produces an incorrect result in the case shown.

The map implementations seems to be provided by BTraceMap, but I did not spot any syncronization.
Does BTrace provides some synchronization I missed to guarantee that accessing a single HashMap from several threads is safe?

What do you propose to solve the check-then-act problem?
If BTrace internally would synchronizes each access to the Map, it could enough to offer methods like computeIfAbsent.
If synchronization is missing, probably access to ConcurrentHashMap would be needed.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions