vert.x icon indicating copy to clipboard operation
vert.x copied to clipboard

Memory optimization

Open magicprinc opened this issue 2 years ago • 5 comments

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.

magicprinc avatar Nov 26 '23 13:11 magicprinc

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 avatar Dec 01 '23 16:12 tsegismont

@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.

varhandle

PS: @franz1981 A humble question to you 🙏 Why do they use volatile int in AtomicBoolean instead of volatile byte?

  • int is faster than byte
  • VarHandle doesn't work with byte
  • byte has no sense because of JVM field alignment
  • they don't care 4 bytes or 1 byte

magicprinc avatar Dec 01 '23 17:12 magicprinc

@franz1981 Could you help please

magicprinc avatar Dec 08 '23 12:12 magicprinc

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 avatar Dec 08 '23 13:12 franz1981

@franz1981 ❤🙏 In case of AtomicBoolean this is obvious. I mean for Vert.x classes with more than one field

magicprinc avatar Dec 08 '23 14:12 magicprinc