Sometimesitisusefullifwecancapturethestateoftheapplication,itsstackoffunctioncalls,whichincludeslocalvariables,theglobalvariablesandtheprogramcounter,andsavethemintoanobject.Ifthisobjectwouldgiveustheabilitytorestarttheprocessingfromthepointstoredinit.
Acontinuationisexactlythetypeofobjectthatweneed.Thinkofacontinuationasanobjectthat,foragivenpointinyourprogram,containsasnapshotofthestacktrace,includingallthelocalvariables,andtheprogramcounter.Youcannotonlystorethesethingsinthecontinuationobject,butalsorestoretheexecutionoftheprogramfromacontinuationobject.Thismeansthatthestacktraceandtheprogramcounteroftherunningprogrambecometheonesstoredinacontinuation.
Continuationsarepowerfulconceptsfromtheworldoffunctionallanguages,likeScheme,buttheyarebecomingpopularinotherlanguagesaswell.
示例代码:
classMyRunnableimplementsRunnable{publicvoidrun(){System.out.println("started!");for(inti=0;i<10;i++)echo(i);}privatevoidecho(intx){System.out.println(x);Continuation.suspend();}}Continuationc=Continuation.startWith(newMyRunnable());System.out.println("returnedacontinuation");
评论