2

I am trying to create a dynamically-loaded set of Scala classes (and objects), held in a 'sandbox' by a ClassLoader (all memory, resources, threads, etc. held within the sandbox). When refreshed, I want all memory/static objects held in the class loader to be dropped. Specifically I don't want any Scala Objects hanging around.

I thought the code below should do that, but after the refresh it doesn't successfully reload the objects.

(package worker)

case class Hello {
    println("Hello!  "+Bee.howBig)
}

object Bee {

  val block = 600000

  println("Building...")
  val s = k5(0)
  println("Built big data!")

  def howBig = s.size 
  def k5(startFrom:Int) = (for(x <- startFrom to (startFrom+block)) yield { (x,java.util.UUID.randomUUID.toString) }).toList
}

(package main)

import worker.Bee
import java.net.URLClassLoader
import java.io._

object Main extends App {
    println("Starting up!")
    var classLoader = new java.net.URLClassLoader(
      Array(new File("worker.jar").toURI.toURL),
      null) // no parent to make it a sandbox (is this right?)

    var helloClass = classLoader.loadClass("worker.Hello")// + "$")
    var hello = helloClass.newInstance
    // This works...I get the output indicating Bee's data has been created

    println("\nand again...")
    classLoader = null  // force the point--refresh here!  hello/bee should be freed
    classLoader = new java.net.URLClassLoader(
      Array(new File("worker.jar").toURI.toURL),
      null)

    var helloClass2 = classLoader.loadClass("worker.Hello")// + "$")
    hello = helloClass2.newInstance
    // This hangs.  Output's "Building..." and nothing else...like it ran out
    // of memory or something...makes me wonder if resources from first CL were
    // ever really dropped
}
Greg
  • 10,696
  • 22
  • 68
  • 98

0 Answers0