raphw / byte-buddy

Runtime code generation for the Java virtual machine.
https://bytebuddy.net
Apache License 2.0
6.29k stars 807 forks source link

Can ByteBuddy add synchronized to intercepted setters? #1632

Closed jimshowalter closed 6 months ago

jimshowalter commented 6 months ago

We're using ByteBuddy to track which fields in persistence entities are set.

To do that, we write the field name and value to a map.

To ensure backward-compatibility, we also call the super's setters, which set fields in the base class.

At runtime, the modified methods look like this:

public void setFoo(Long var1) {
    SetterInterceptor.interceptSetter(cachedValue$jbu0XnWD$qevi042, var1, this);
    super.setFoo(var1);
}

But that means they are no longer atomic. Two threads calling the same setter on the same instance of the entity could wind up with different values in the map vs. the original field.

Is there a way to add synchronized to the generated setters in the subclass?

raphw commented 6 months ago

Sure, you can register a Transformer.ForMethod.withModifiers(...) which allows you to add the synchronized flag.

jimshowalter commented 6 months ago

Thank you!