Java - save / restore call stack

Is it possible to save the state of the call stack at runtime and later restore the stack to this state by restarting the call to the highest method?

+4
source share
5 answers

I highly recommend changing your paradigm. Instead of manipulating the call stack (and, most likely, corrupting the JVM), think about somehow incorporating a "call stack" into your algorithm.

You can use the Strategy / Command / Undo strategy template and store objects in your own logical stack, over which you have full control.

.

+10

, , . - :

Result findResult() {
    while (true) {
        Data data = getData();
        try {
            return processData(data);
        } catch (OutOfDateException e) {
            /* fall through */
        }
    }
}

Result processData(Data data) throws OutOfDateException {
    /* ... */
    processData2(otherData)
    /* ... */
}

IntermediateResult processData2(OtherData otherData) throws OutOfDateException {
    /* ... */
    if (myDataWasTooOld())
        throw new OutOfDateException();
    /* ... */
}

, processData2() , (processData2(), processData()) data.

+3

. Thread , . , , -

StackTraceElement[] stack = Thread.currentThread().getStackTrace();

, , . , , , .

0

. , . , , .

- :

public class Debugger implements Serializable {
    private static final long serialVersionUID = 1L;

    private Thread parent;
    private String packageName;
    private File outputFile;
    private boolean alive;

    public Debugger(Thread parent, String packageName, File outputFile) {
        this.parent = parent;
        this.packageName = packageName;
        this.outputFile = outputFile;
        alive = true;
    }

    public void run() throws FileNotFoundException {
        PrintStream ps = new PrintStream(outputFile);
        alive = true;
        String lastClassName = "";
        while (parent.isAlive() && alive) {
            for (StackTraceElement ste : parent.getStackTrace()) {
                if (ste.getClassName().startsWith(packageName)) {
                    if (!ste.getClassName().equals(lastClassName)) {
                        ps.println(ste.toString());
                        lastClassName = ste.getClassName();
                    }
                    break;
                }
            }
        }
        ps.close();
    }

    public void kill() {
        alive = false;
    }
}

, , / . kill() , . , , / , , , , .

( ()), , .

, , , . , .

0

, - ... Java Flow - , , , , - Continuation, - "magic" - , .

http://commons.apache.org/sandbox/commons-javaflow/tutorial.html

0

Source: https://habr.com/ru/post/1541427/


All Articles