shannah / Java-Objective-C-Bridge

A thin bridge that allows for two-way communication from Java to Objective-C.
123 stars 25 forks source link

Remove NSObject.methodMap or make it thread-safe #34

Open Marcono1234 opened 3 years ago

Marcono1234 commented 3 years ago

The field NSObject.methodMap is of type HashMap and is accessed without any synchronization: https://github.com/shannah/Java-Objective-C-Bridge/blob/62409c5ce0b331a455e8a5d98a176e1b70488d63/src/main/java/ca/weblite/objc/NSObject.java#L72

However, if access it correctly synchronized it would still be a memory leak because the map would constantly grow and is never cleared. Would it maybe make sense to make this an instance field (i.e. remove static)? Though I am not very familiar with this project and what performance implications this would have.

shannah commented 3 years ago

The method map serves as a sort of vtable for looking up the Java method to use for handling a given Objective-C method selector. Each subclass of NSObject will have a corresponding entry. Conceptually this is static with a one-to-one correspondence between a Java class and a method table.

To satisfy your concern about growing without bound, perhaps it should be changed to a WeakHashMap so that if the class is GC'd, its method table will be cleaned up.

Marcono1234 commented 3 years ago

Ah, right then it would likely not be a memory leak because there will only be a limited amount of classes. But using a WeakHashMap might be useful nonetheless to allow removal when a custom class loader which loaded the class is unloaded? However, that might make synchronization more complicated / inefficient.