Giter Club home page Giter Club logo

java-continuation's Introduction

Simulating Continuation in Java Via Threads and Trampoline Pattern

Using Threads


Following is an example of how to use the Continuation.java. Its constructor receives a Runnable as the body of the routine that calls yield(s).
The very first goOn() call would start running the Runnable until it yields upon which the control is transferred back to the main routine where goOn() was invoked. This ping pong transfer of control between main and sub routine continues until Runnable finishes through the very last yield() call.

Continuation<Integer> cont;
...
cont = new Continuation<>(
    () -> {
        //Sub Routine
        System.out.println("2:subRoutine");
        cont.yield(1);   //return 1
        System.out.println("4:subRoutine");
        cont.yield(2);   //return 2
        System.out.println("6:subRoutine");
        cont.yield(3);   //return 3
    }
);

//Main Routine
int result;
System.out.println("1:mainRoutine");
result = cont.goOn();   //result = 1
System.out.println("3:mainRoutine");
result = cont.goOn();   //result = 2
System.out.println("5:mainRoutine");
result = cont.goOn();   //result = 3
System.out.println("7:mainRoutine");

/*
    Output:
        1:mainRoutine
        2:subRoutine    
        3:mainRoutine
        4:subRoutine
        5:mainRoutine
        6:subRoutine
        7:mainRoutine
*/

Generator.java utilizes Continuation.java to implement Iterable interface and act as a lazy generator. Its yield() method emits values as the Iterator asks for next value.

Note: The current Iterable and Iterator implementation is incomplete and does not comply with the specifications completely. For example it requires hasNext() method to be called before every next() call.

Bellow is an example of a generator that can emit integers starting from 0 up to Long.MAX_VALUE in a lazy way.

Generator<Long> intGenerator;
...
intGenerator = new Generator<>(
    () -> {
        for(long i=0; i<Long.MAX_VALUE; i++) {
            intGenerator.yield(i);
        }    
    }        
);

for(int j: intGenerator)
    if(j <= 100) System.out.println(j);
    else break;

Following is the stripped down version of the Continuation.java to provide an idea on how the yield mechanism is simulated. Note that goOn() and yield() methods are being called from two different threads. using lock and conditions the class simulates the back and forth transfer of control between two different routines.

public void yield(T value) throws InterruptedException {
    try {
        this.value = value;
        lock.lock();
        mainRoutineCondition.signal();
        subRoutineCondition.await();
    }finally {
        lock.unlock();
    }
}

public T goOn() throws InterruptedException {
    value = null;
    try {
        lock.lock();
        if (subRoutineThread.getState() == Thread.State.NEW) {
            subRoutineThread.start();
        } else subRoutineCondition.signal();
        mainRoutineCondition.await();
        return value;
    }finally {
        lock.unlock();
    }
}

Using Trampoline


Continuation<Integer> myCont = new Continuation<Integer>() {
    int i = -1;

    @Override
    public Integer start() {
        i++;
        if(i < 100) {
            thenRun(this::next);
        }
        return i;
    }
};

IntStream.range(0, 10000).forEach(
        i -> System.out.println(myCont.goOn())
);

java-continuation's People

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.