0

I am generating Java code on the fly which will then be compiled and loaded back in. My issues is that I essentially need jumps because when I return from the function I wish to continue execution from the point in the loop from where I have exited. Hopefully, the code here illustrates my desire. Although the actual code will have some ifs as well and be much deeper.

MyIter a,b,c;

boolean func() {
 jump to correct state here

 state0:

 a = ...;
 while (a.next()) {
   state1: while (b.next()) {
     return true; // start again at state1
   }
   b = ...;
 }

 c = ...;
 state2:
 while (c.next()) {
   return true; // start again at state2
 }
 return false;
}

In C I would probably use a jump table and state variable. Performance is the key here and the code interacts with the Java application.

My best guesses so far have been:

  • Flipping the nesting of loops and the logic. That became too cumbersome and problematic.
  • Adding logic to allow the flow to get back to where it was but this may be messy.
  • I assume the bytecode can jump so I could generate the bytecode myself but that doesn't seem ideal (is there any good libraries for this?)
  • Continuation passing style to avoid returning but that would involve major restructuring, although currently the likely way to go.

I was wondering if anyone had any thoughts?

Molehill
  • 35
  • 6
  • 1
    I think you'll have a hard time doing jumps even in bytecode - the verifier has all sorts of rules that make bytecode a lot less flexible than you might think. – Tom Anderson Jan 08 '11 at 21:17

2 Answers2

2

The simplest option is to use a switch block (or if you have to, nested switch statements)

enum State {
   state1, state2, state3;
}

State state = State.state1;

public boolean func() {
   while(true) {
     switch(state) {
        case state1:
            if(test()) return true;
            state = state2;
            break;
        case state2:
            if(test2()) return false;
            state = state3;
            break;
        case state3:
            if(test3()) return true;
            state = state1;
            break;
      }
   }
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Thanks. After playing and thinking a little more this looks the best option for my purposes. A quick implementation is working well, although sadly it will be nested at times. – Molehill Jan 09 '11 at 03:23
  • You may be able to flatten the states by having state3_1, state3_2, ... state3_N. That may or may not make things clearer. – Peter Lawrey Jan 09 '11 at 08:44
0

A Java coroutine library might suit your purposes. See this related StackOverflow question for some pointers.

Community
  • 1
  • 1
Brian Clapper
  • 25,705
  • 7
  • 65
  • 65