Я хотел бы реализовать батут в java, возвращая thunk всякий раз, когда я нажимаю StackOverflowError. Есть ли какие-либо гарантии в отношении StackOverflowError, например, если я только что сделаю после того, как StackOverflowError создает объекты в куче и возвращается из функций, я буду в порядке?
Если выше сказанное нечетко, я добавил некоторый код для вычисления четного/нечетного в хвостовой рекурсивной манере в стиле продолжения передачи, возвращая задержанный thunk всякий раз, когда стек течет. Код работает на моей машине, но гарантирует ли Java, что он всегда будет работать?
public class CPS {
public static class Thunk {
final Object r;
final Continuation c;
final boolean isDelayed;
public Object force() {
Thunk t = this;
while (t.isDelayed)
t = t.compute();
return t.r;
}
public Thunk compute() {
return this;
}
public Thunk(Object answer) {
isDelayed = false;
r = answer;
c = null;
}
public Thunk(Object intermediate, Continuation cont) {
r = intermediate;
c = cont;
isDelayed = true;
}
}
public static class Continuation {
public Thunk apply(Object result) {
return new Thunk(result);
}
}
public static Thunk even(final int n, final Continuation c) {
try {
if (n == 0) return c.apply(true);
else return odd(n-1, c);
} catch (StackOverflowError x) {
return new Thunk(n, c) {
public Thunk compute() {
return even(((Integer)n).intValue(), c);
}
};
}
}
public static Thunk odd(final int n, final Continuation c) {
try {
if (n == 0) return c.apply(false);
else return even(n-1, c);
} catch (StackOverflowError x) {
return new Thunk(n, c) {
public Thunk compute() {
return odd(((Integer)n).intValue(), c);
}
};
}
}
public static void main(String args[]) {
System.out.println(even(100001, new Continuation()).force());
}
}