views:

119

answers:

4

Hi!

I just read the Trail on RMI from sun at http://java.sun.com/docs/books/tutorial/rmi/implementing.html

When I run the example, the JVM does not terminate although main has finished. Is RMI spawning a Thread somewhere internally?

What is the behaviour of multiple Threads spawned in main, after main exits? Is it a clean way to let the Threads exit whenever they want or should you do a join on each Thread you spawn? I did not find any documentation on this question.

Thank you very much for your help!!

public class ComputeEngine implements Compute {

    public ComputeEngine() {
        super();
    }

    public <T> T executeTask(Task<T> t) {
        return t.execute();
    }


    public static void main(String[] args) {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }
        try {
            String name = "Compute";
            Compute engine = new ComputeEngine();
            Compute stub = (Compute) UnicastRemoteObject.exportObject(engine, 0);
            Registry registry = LocateRegistry.getRegistry();
            registry.rebind(name, stub);
            System.out.println("ComputeEngine bound");
        } catch (Exception e) {
            System.err.println("ComputeEngine exception:");
            e.printStackTrace();
        }
    }
}
+3  A: 

A thread is created for listening the socket and reply to requests to your object. One way to stop the JVM is to unbind the server (Registry.unbind()) and unexport the objects (UnicastRemoteObject.unexportObject()).

Kartoch
Thanks for your answer!Is this a clean way?Should not the main Thread wait for exiting all Threads? (second question above)
Flo
Well, the only problem is "when do you want to stop your application ?". For instance, you can decide to unexport and unbind when you received a specific message.
Kartoch
+1  A: 

Yes, when you are exposing objects through RMI it needs a thread to accept incoming requests for these objects. This thread could be a daemon thread which wouldn't stop the JVM from exiting but it isn't for several reasons and as long as there are still active exported objects it hinders the JVM from exiting normally. So you can use unexportObject for all objects or just use System.exit() to end the JVM although this would leave the clients uninformed about the shutdown.

x4u
+1  A: 

You can use the jstack utility program, included in the JDK to see which threads are running in a java program, and even what line those threads are on.

So if you're program is still running you just run jstack on the pid and it will tell you which threads are still running and what they're doing.

Chad Okere
+2  A: 

Concerning the "behaviour of multiple threads" part of your question: yes, the JVM will keep on running until all threads finished. The only exception are threads marked as daemon (see Thread.setDaemon()), the JVM will not wait for them.

Tim Jansen