vert.x
vert.x copied to clipboard
Memory optimization
There is a memory optimization that can be used in Vert.x in several places.
For example, here:
io.vertx.core.impl.VertxImpl.InternalTimerHandler
private final AtomicBoolean disposed = new AtomicBoolean();
AtomicBoolean is quite a heavy object (many times bigger than volatile boolean)
It can be replaced with VarHandle. The VarHandle has all the same operations, but it is a static field member of a class and in object there is only a volatile byte or int field. You can see this technic in JDK
java.util.concurrent.FutureTask#set
Replacing Atomic* with VarHandle and volatile in libraries makes sense.
It dramatically reduces the memory footprint without disadvantages.
I could make a PR for InternalTimerHandler.
yes perhaps that could be useful for InternalTimerHandler because we create a lot of them
@franz1981 are you aware of any performance implications on using Varhandle vs atomicboolean for CAS?
@tsegismont I am not an expert as the famous @franz1981 is, but I can add: Atomic* uses VarHandle internally (sometimes still mixed with Unsafe 😅 ). You can copy the working code directly from an Atomic* implementation. The only disadvantage I know: more code on your side.
PS: @franz1981 A humble question to you 🙏
Why do they use volatile int in AtomicBoolean instead of volatile byte?
intis faster thanbyteVarHandledoesn't work withbytebytehas no sense because of JVM field alignment- they don't care 4 bytes or 1 byte
@franz1981 Could you help please
I think https://github.com/openjdk/jdk/blob/701bc3bbbe49a46aea7efc195463cc2efd64a785/src/java.base/share/classes/jdk/internal/vm/SharedThreadContainer.java#L46 shows that you could use byte-level var handle, but if you use Java Object Layout to print the layout of AtomicBoolean, having less than int doesn't improve the footprint of the class (which are usually aligned at 8-16 bytes in size AND have different aligned layout based on the class header size). So they didn't see any value to change it to use a boolean/byte.
@franz1981 ❤🙏 In case of AtomicBoolean this is obvious. I mean for Vert.x classes with more than one field