Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

56
LINES

< > BotCompany Repo | #1035329 // LASMultiClassLoader

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (11152L/64K).

// Idea: Every class loader makes only a single class  so they can be
// garbage collected more easily.

srecord noeq LASMultiClassLoader(ClassLoader parent) is ILASClassLoader, AutoCloseable {
  settable bool rememberClassBytes;
  
  new WeakValueMap<S, Class> definedClasses;
  Lock lock = lock();
  
  event classDefined(Class c);
  
  *(Class parent) { this(parent.getClassLoader()); }
  
  {
    definedClasses.onValueForKeyReleased(key -> 
      printWithMS(":: CLASS UNLOADED :: " + key));
  }
  
  selfType runnablesReferenceQueue(RunnablesReferenceQueue queue)  {
    definedClasses.queue(queue);
    this;
  }
  
  int nClassesLoaded() { ret l(definedClasses); }
  
  Cl<Class> definedClasses() {
    ret values(definedClasses.snapshot());
  }
  
  public Class<?> defineLASClass(S name, IF0<byte[]> generateClass) {
    lock lock;
    
    try object definedClasses.get(name);
    
    var cl = new IndividualClassLoader().rememberClassBytes(rememberClassBytes);
    print("Generating class " + name);
    Class c = cl.defineAClass(name, generateClass!);
    definedClasses.put(name, c);
    classDefined(c);
    ret c;
  }
  
  close {
    dispose definedClasses;
  }
  
  class IndividualClassLoader extends InMemoryClassLoader {
    *() { super(parent); }
    
    // Allows one script-defined class to see another one
    protected Class<?> findClass(S name) throws ClassNotFoundException {
      try object definedClasses.get(name);
      ret super.findClass(name);
    } 
  }
}

Author comment

Began life as a copy of #1035083

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, ekrmjmnbrukm, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1035329
Snippet name: LASMultiClassLoader
Eternal ID of this version: #1035329/16
Text MD5: cb12f50bc3481d766a0626dd732fba7f
Transpilation MD5: 4879bf0ec62bed41b42c5fa6915fd135
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-12-13 19:21:14
Source code size: 1549 bytes / 56 lines
Pitched / IR pitched: No / No
Views / Downloads: 194 / 340
Version history: 15 change(s)
Referenced in: [show references]