4

I was wondering if there's a good way of doing this. I've got a List of Runnable objects but I can't let them run now because my server is shutting down. They must be stored on the disk so that next time when the server is up, the threads can run again.

I don't need to remember their status. All I want is to be able to rerun the threads. I got lost in terms of where to start. Any suggestions will be appreciated.

goldfrapp04
  • 2,326
  • 7
  • 34
  • 46

1 Answers1

4

With Java 8, you can create Runnables from lambda expressions, which are serializable. For example:

Runnable r = (Runnable & Serializable) () -> yourRunMethodHere();
try (ObjectOutput oo = new ObjectOutputStream(new FileOutputStream(file))) {
    oo.writeObject(r);
}

Retrieving the Runnable and running it can then be done with:

try (ObjectInput oi = new ObjectInputStream(new FileInputStream(file))) {
    Runnable  r = (Runnable) oi.readObject();
    r.run();
}

I don't think Java 7 provides an elegant solution for that problem.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
  • Unfortunately we haven't updated to Java 8 yet. I guess I should consider getters for critical data from the Runnable and reconstruct threads when needed. – goldfrapp04 May 20 '14 at 23:26