2

I admit, if it's possible, it would be open door to bad, very bad code... But in some specific cases...

So the question is, is there any equivalent of setjmp/longjmp ?

I would like to implement a python-like generator without using threads, just saving the stack and the context, and restore it later.

fuz
  • 88,405
  • 25
  • 200
  • 352
hl037_
  • 3,520
  • 1
  • 27
  • 58
  • Yes. The mechanism is called *exceptions.* – fuz Dec 26 '15 at 11:11
  • 2
    No. Exception can use this mechanism, but exception are mainly an error handling system. setjmp/longjmp permits also to do coroutines that, except if you can prove otherwise, is not possible using exceptions – hl037_ Dec 26 '15 at 11:15
  • Exceptions are slightly more structured long jumps. Nothing more, nothing less. They are typically used for error handling, but that's not imperative. – fuz Dec 26 '15 at 11:16
  • @FUZxxl - You miss the point. There are lots of things that you can do with setjmp/longjmp that you cannot do with Java exceptions. – Stephen C Dec 26 '15 at 12:02
  • @StephenC I know that you can hack some sort of coroutine system with setjmp/longjmp, but these are not portably uses of setjmp and in fact modern libc's crash the program if such misuse is detected. – fuz Dec 26 '15 at 12:06
  • 2
    @hl037_ This is very much an XY question - you're asking about a feature because you want to make a solution to a problem based on your knowledge from the other language. There are alternatives in java. – Anya Shenanigans Dec 26 '15 at 13:43
  • @Petesh I think you're right : since I don't like java and I tried to use techniques from other language. Kind of frustrating there is no portable coroutines system on java. Anyway, I was able to do what I needed here with a custom iterator (I knew it was possible this way, I just wanted to ask if there were such a system to do python like generator in the future) – hl037_ Dec 26 '15 at 14:00

2 Answers2

3

While not strictly equivalent to the C longjump, the Javaflow library from apache commons gives a way to interrupt a code flow (like Exceptions do, but with capture of the stack), and to restart it later. This is suitable to implements Coroutines. However, it requires bytecode modification.

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

2

Simple answer: No there is not! The closest thing you can get are labeled breaks, which are a kind of forward jumps to break out of multiple nested blocks, but thats it!

loonytune
  • 1,775
  • 11
  • 22