1515import io .vertx .core .impl .logging .LoggerFactory ;
1616
1717import java .util .LinkedList ;
18+ import java .util .concurrent .CountDownLatch ;
1819import java .util .concurrent .Executor ;
1920import java .util .concurrent .RejectedExecutionException ;
20- import java .util .function . Consumer ;
21+ import java .util .concurrent . TimeUnit ;
2122
2223/**
2324 * A task queue that always run all tasks in order. The executor to run the tasks is passed
@@ -82,17 +83,12 @@ private void run() {
8283 }
8384
8485 /**
85- * Unschedule the current task from execution, the next task in the queue will be executed
86- * when there is one.
86+ * Return a controller for the current task.
8787 *
88- * <p>When the current task wants to be resumed, it should call the returned consumer with a command
89- * to unpark the thread (e.g most likely yielding a latch), this task will be executed immediately if there
90- * is no tasks being executed, otherwise it will be added first in the queue.
91- *
92- * @return a mean to signal to resume the thread when it shall be resumed
88+ * @return the controller
9389 * @throws IllegalStateException if the current thread is not currently being executed by the queue
9490 */
95- public Consumer < Runnable > unschedule () {
91+ public WorkerExecutor . TaskController current () {
9692 Thread thread ;
9793 Executor executor ;
9894 synchronized (tasks ) {
@@ -101,20 +97,42 @@ public Consumer<Runnable> unschedule() {
10197 }
10298 thread = currentThread ;
10399 executor = currentExecutor ;
104- currentThread = null ;
105100 }
106- executor .execute (runner );
107- return r -> {
108- synchronized (tasks ) {
109- if (currentExecutor != null ) {
110- tasks .addFirst (new ResumeTask (r , executor , thread ));
111- return ;
112- } else {
101+ return new WorkerExecutor .TaskController () {
102+
103+ final CountDownLatch latch = new CountDownLatch (1 );
104+
105+ @ Override
106+ public void resume (Runnable callback ) {
107+ Runnable task = () -> {
108+ callback .run ();
109+ latch .countDown ();
110+ };
111+ synchronized (tasks ) {
112+ if (currentExecutor != null ) {
113+ tasks .addFirst (new ResumeTask (task , executor , thread ));
114+ return ;
115+ }
113116 currentExecutor = executor ;
114117 currentThread = thread ;
115118 }
119+ task .run ();
120+ }
121+
122+ @ Override
123+ public CountDownLatch suspend () {
124+ if (Thread .currentThread () != thread ) {
125+ throw new IllegalStateException ();
126+ }
127+ synchronized (tasks ) {
128+ if (currentThread == null || currentThread != Thread .currentThread ()) {
129+ throw new IllegalStateException ();
130+ }
131+ currentThread = null ;
132+ }
133+ executor .execute (runner );
134+ return latch ;
116135 }
117- r .run ();
118136 };
119137 }
120138
0 commit comments