Continuation is a technique through which we can store and retrieve the execution state of the program at some particular point. It means that we can pause the program at a specific point and save the program state at that point. Then continue the program flow from that point with the same or some modified input.
So continuation saves the context of the program flow at a specific point. Context includes variables, the call stack state, and the point of execution. Afterward, you can restore the state that you have saved and can continue the program execution.
Note: Java programming language does not natively support continuation but we can achieve continuation in Java through different techniques.
This tutorial will explain the concept of continuation in Java.
What is a Virtual Threads and Continuation in Java?
In Java, there is a term called “virtual threads” which was first introduced in “Java 19”. Virtual threads use continuation for their implementation. These threads are not managed by any operating systems because Java Virtual Machine (JVM) manages it itself. These virtual threads are so lightweight that they can be more easily created and destroyed than the other traditional threads.
A new continuation is created as soon as a virtual thread is created and the current state of the thread is then captured and stored by the continuation for using it later. It enables the creation and management of a larger number of concurrent threads for the application and hence improves the performance of the application.
Working of Virtual Threads:
As we understood what are virtual threads now, we will discuss how it works:
- When a virtual thread is created its continuation is created.
- The continuation saves the current state of the virtual thread.
- If there is any I/O operation that needs to be performed then it is required to suspend the virtual thread.
- When a virtual thread is suspended, the current state is saved in the heap of continuation.
- When the I/O operation ends, the state of the virtual thread is restored from the heap of continuation and the virtual thread resumes its execution.
That’s it! We have described the continuation in Java.
Conclusion
Continuation is the process through which the current state of the program is saved at a particular point and then used after a certain period of time or when it is required. In Java, there are certain techniques to achieve continuation. Virtual threads are implemented in Java through continuation and managed by Java Virtual Machine(JVM). That’s all about the continuation of Java.