Workaround for slow Redefine / Retransform

2019-08-23 05:37发布

问题:

Unfortunately calling redefine / retransform on a big number of classes is kind of slow and can easily take multiple minutes. There was even a bug raised some time ago which was closed as "won't fix": JDK-6173565 : RedefineClasses must be fast even when hundreds or thousands of classes are redefined (Note: I know it's an old bug, but even using JDK8 it is sill very slow; ~2min for ~4500 classes)

I'm having a use case where I ideally need to be able to switch quickly between the original version of some classes and the instrumented ones.

One "solution" I was thinking of is to simply weave an if-else statement to the methods and pretty much duplicate the method body; with the if block containing the original version and the else the modified version. But that would impact every method of the application code, so I expect some overhead even for always running through the ifs. Not sure yet how the jit will be able to optimize that. According to quick JMH test the overhead of calling a simple getter method with an "if" inside is roughly 4-5%. Of course in a real application that should be a little less as there are more instructions to be executed than in my stupid test case, but nevertheless not sure if that is a good way to approach the problem.

Any other idea how I could prevent having to wait multiple minutes when the fuctionality is enabled and disabled?