1

In a current project, I am attempting to load a set of plugins; The problem is that plugin could do anything, include throwing exceptions, or just hanging forever. I am trying to accomplish the following:

try {

    // load class by package name
    Class<?> pluginClass = Class.forName(plginClassName);

    // create a new instance of the object
    // this call could throw an exception or never return
    GenericPlugin plugin = (GenericPlugin) pluginClass.newInstance();

    state = PluginState.INITIALIZED;
    ...

} catch ( InterruptedException ie ) {  // <-- Compile Error Here
// Unreachable catch block for InterruptedException. This exception is never thrown from the try statement body

    state = PluginState.TIMEOUT;
} catch ( Exception ex ) {

    state = PluginState.FAILED;
}

I would like it such that in my calling class of the loader thread I can do:

LoaderThread t = new LoaderThread( pluginClassName );

// start loading the plugin
t.start();

// wait 5 seconds for startup
t.join( 5000 );

// interrupt if not complete
t.interrupt();

// get my plugin state
pluginState = t.getPluginState();

If i am going at this wrong, please advise, but

How can I timeout a call to class.newInstance()?

Matt Clark
  • 27,671
  • 19
  • 68
  • 123
  • 2
    You can only catch `InterruptedException` from a method that explicitly throws it. Usually that's the case for methods that are meant to block, like concurrent utilities or I/O. Otherwise, you'll need to check for interrupted state manually (`Thread.currentThread.isInterrupted()`). If the code that's hanging is out of your control, the best you can do is try to interrupt and hope someone in there is listening. – shmosel Feb 28 '17 at 01:47
  • I've changed up the actual question slightly, would there be any way of simply timing out the call to `newInstance()`? – Matt Clark Feb 28 '17 at 02:00
  • 1
    Your code already times out by calling `t.join(5000)`. But can't safely *kill* a thread without its cooperation. See http://stackoverflow.com/questions/16504140/thread-stop-deprecated – shmosel Feb 28 '17 at 02:03

0 Answers0