Skip to content

Instantly share code, notes, and snippets.

@nerdyworm
Created January 28, 2011 17:29
Show Gist options
  • Save nerdyworm/800601 to your computer and use it in GitHub Desktop.
Save nerdyworm/800601 to your computer and use it in GitHub Desktop.
A super simple coroutine explanation of a coroutine in java.
This solution is incorrect and is only meant to be a clarification
of a problem discussed between two friends. It will consume the
stack until a stack overflow if the limit is set to high. True
coroutines are only possible in java using threads, native code or
bytecode manipulation. If there is a librarless way to create a
coroutine in java please fork and contribute.
public class Blah {
int limit = 500;
int count = 0;
int B, X, Y, Z;
int c_state = 0, p_state = 0;
public void resume(String function) {
if(function == "producer") {
producer();
}
if(function == "consumer") {
consumer();
}
}
public void consumer() {
switch(c_state++) {
case 0:
X = B;
resume("producer");
break;
case 1:
Y = B;
resume("producer");
break;
case 2:
Z = B;
System.out.printf("x = %d, y = %d, z = %d\n", X, Y, Z);
c_state = 0;
if(count++ < limit)
resume("producer");
break;
}
}
public void producer() {
switch(p_state++) {
case 0:
B++;
resume("consumer");
break;
case 1:
B++;
p_state = 0;
resume("consumer");
break;
}
}
public static void main(String[] args) {
Blah b = new Blah();
b.resume("producer");
}
}
@HeinerKuecker
Copy link

Is this little lib a solution for you:
HeinerKuecker/Coroutine-in-pure-Java

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment