views:

47

answers:

1

My shutdown hooks will not run. The shutdown hook is intended to print out statistics after the program has terminated for all philosopher threads that had been running. The philosopher class extends Thread, and simply chews and eats based on if forks are available or not. Here is my code.

public class Main {
    private static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();

public static void main(String[] args) {
    int counter = 0;
    int num = Integer.parseInt(args[0]); // number of philosopher threads to create
    for(int x = 0; x < num; x++)
    {
        Fork one = new Fork(counter);
        counter++;
        Fork two = new Fork(counter);
        counter++;
        Philosopher p = new Philosopher(String.valueOf(x), one, two); // (Identifier, fork one, fork two)
        philosophers.add(p);
    }

    // Create shutdown hook
    Stats s = new Stats(philosophers);
    Runtime.getRuntime().addShutdownHook(s);

    // Start all philosopher threads
    for(Philosopher phil : philosophers)
    {
        phil.start();
    }
}
}


public class Stats extends Thread{
    private ArrayList<Philosopher> list = new ArrayList<Philosopher>();

    public Stats(ArrayList<Philosopher> al)
    {
        list = al;
    }

    public void run()
    {
        System.out.println("Test");
        for(Philosopher p : list)
        {
            System.out.println(p.getPhilName() + " thought for " + p.getTimeThinking() + " milliseconds and chewed for " + p.getTimeChewing() + " milliseconds.");
        }
    }
}

Thanks for any help you can provide, I greatly appreciate it.

+1  A: 

You're creating Philosopher instances but are not adding them to list, hence the list remains empty and your shut-down hook appears not to run because it won't print anything to stdout.

EDIT

Following your recent comment the next thing I'd suggest is to add logging to prove that all threads are terminating. For example, you could join with each philosopher thread from your main thread so that when your main thread terminates you are certain that each philosopher thread has previously terminated.

  // Start all philosopher threads
  for (Philosopher phil : philosophers) {
    phil.start();
  }

  for (Philosopher phil : philosophers) {
    System.err.println("Joining with thread: " + phil.getName());
    phil.join();
  }

  System.err.println("Main thread terminating.");
  // Shut-down hook should now run.
}
Adamski
I apologize, I was trying to remove as much as code as possible to make it easier to read, and accidentally removed that line. I am adding to the list in my program, and it is still not working.
OogaBooga
See my latest edit.
Adamski