Continuation Passing Style

Continuation Passing Style

In Continuation Passing Style (CPS), the program is comprised of several continuations. The methods in CPS programming do not return a value, rather, they pass control (including the current context) to the next continuation.

Each continuation receives a context, which stores the state of the current chain of continuations at a given time, and can alter this context and call the next continuation. There can exist different types of continuations too, for handling exceptions, suspending the program, or simply calling other continuations.

In some functional programming languages CPS is supported and can be used in conjunction with tail-call optimization to try to control the call stack size.

Use cases of CPS in Java

Apache Commons contains a component in its sandbox, Apache Commons JavaFlow, that hasn’t been updated in a while, but that supports continuations in Java. It requires the code to be instrumented, and provides ways to restore the execution of the code.

The Jenkins Workflow Plug-in was presented during the Jenkins User Conference 2014 in Boston. The plug-in has several Maven modules, among is the cps Maven module. This maven module provides CPS to the plugin. If you take a look at the team page of the JavaFlow project, you will find it interesting that Kohsuke Kawaguchi (Jenkins creator) is listed there too :-)

From what I could tell, the Jenkins Workflow Plug-in utilizes CPS to break down the workflow execution in several continuations, that are persisted to the disk and can be resumed in case the job execution is interrupted.

There are several differences between the cps module and Apache Commons Javaflow - such that in the latter the running code needs to be instrumented. I haven’t investigated all of them yet, but it sounds very interesting! I’m waiting for one of those rainy weekends so that I can spend many hours reading the code of the two and taking notes.

Final thoughts

CPS is a very interesting concept, and while probably the enterprise Java developer is not going to use it for his every day corporate web application (though some FP programmers might be using it), it is an interesting technique that can probably be applied in some specific scenarios - as it was in the Jenkins Workflow Plug-in.

There are optimizations available for CPS 12 too, so I believe the workflow-plugin has space for more innovation, and lots of fun for hackers.

Happy hacking!