How to use DeltaQueue class of org.jmock.lib.concurrent.internal package

Best Jmock-library code snippet using org.jmock.lib.concurrent.internal.DeltaQueue

Run Jmock-library automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1/*
2 * (c) Copyright 2020 Palantir Technologies Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.palantir.dialogue.core;
18
19import java.time.Duration;
20import java.util.Collection;
21import java.util.List;
22import java.util.concurrent.Callable;
23import java.util.concurrent.Delayed;
24import java.util.concurrent.ExecutionException;
25import java.util.concurrent.Executor;
26import java.util.concurrent.ExecutorService;
27import java.util.concurrent.Future;
28import java.util.concurrent.ScheduledExecutorService;
29import java.util.concurrent.ScheduledFuture;
30import java.util.concurrent.TimeUnit;
31import java.util.concurrent.TimeoutException;
32import org.jmock.lib.concurrent.DeterministicExecutor;
33import org.jmock.lib.concurrent.UnsupportedSynchronousOperationException;
34import org.jmock.lib.concurrent.internal.DeltaQueue;
35
36/**
37 * Modified from https://github.com/jmock-developers/jmock-library/blob/498d09a015205f1370bf3855d59db033cf541c3c/jmock/src/main/java/org/jmock/lib/concurrent/DeterministicScheduler.java
38 * Modification is proposed upstream:
39 * https://github.com/jmock-developers/jmock-library/issues/172
40 * https://github.com/jmock-developers/jmock-library/pull/173
41 *
42 * Copyright (c) 2000-2017, jMock.org
43 * All rights reserved.
44 *
45 * Redistribution and use in source and binary forms, with or without
46 * modification, are permitted provided that the following conditions are
47 * met:
48 *
49 * Redistributions of source code must retain the above copyright notice,
50 * this list of conditions and the following disclaimer. Redistributions
51 * in binary form must reproduce the above copyright notice, this list of
52 * conditions and the following disclaimer in the documentation and/or
53 * other materials provided with the distribution.
54 *
55 * Neither the name of jMock nor the names of its contributors may be
56 * used to endorse or promote products derived from this software without
57 * specific prior written permission.
58 *
59 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
60 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
61 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
62 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
63 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
64 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
65 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
66 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
67 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
68 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
69 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
70 *
71 * A {@link ScheduledExecutorService} that executes commands on the thread that calls
72 * {@link #runNextPendingCommand() runNextPendingCommand}, {@link #runUntilIdle() runUntilIdle} or
73 * {@link #tick(long, TimeUnit) tick}.  Objects of this class can also be used
74 * as {@link Executor}s or {@link ExecutorService}s if you just want to control background execution
75 * and don't need to schedule commands, but it may be simpler to use a {@link DeterministicExecutor}.
76 *
77 * @author nat
78 */
79public final class NanosecondPrecisionDeterministicScheduler implements ScheduledExecutorService {
80    private final DeltaQueue<ScheduledTask<?>> deltaQueue = new DeltaQueue<>();
81
82    /**
83     * Runs time forwards by a given duration, executing any commands scheduled for
84     * execution during that time period, and any background tasks spawned by the
85     * scheduled tasks.  Therefore, when a call to tick returns, the executor
86     * will be idle.
87     */
88    public void tick(long duration, TimeUnit timeUnit) {
89        long remaining = toTicks(duration, timeUnit);
90
91        do {
92            remaining = deltaQueue.tick(remaining);
93            runUntilIdle();
94
95        } while (deltaQueue.isNotEmpty() && remaining > 0);
96    }
97
98    /**
99     * Runs all commands scheduled to be executed immediately but does
100     * not tick time forward.
101     */
102    public void runUntilIdle() {
103        while (!isIdle()) {
104            runNextPendingCommand();
105        }
106    }
107
108    /**
109     * Runs the next command scheduled to be executed immediately.
110     */
111    public void runNextPendingCommand() {
112        ScheduledTask<?> scheduledTask = deltaQueue.pop();
113
114        scheduledTask.run();
115
116        if (!scheduledTask.isCancelled() && scheduledTask.repeats()) {
117            deltaQueue.add(scheduledTask.repeatDelay, scheduledTask);
118        }
119    }
120
121    /**
122     * Reports whether scheduler is "idle": has no commands pending immediate execution.
123     *
124     * @return true if there are no commands pending immediate execution,
125     *         false if there are commands pending immediate execution.
126     */
127    public boolean isIdle() {
128        return deltaQueue.isEmpty() || deltaQueue.delay() > 0;
129    }
130
131    @Override
132    @SuppressWarnings("FutureReturnValueIgnored")
133    public void execute(Runnable command) {
134        schedule(command, 0, TimeUnit.SECONDS);
135    }
136
137    @Override
138    public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
139        ScheduledTask<Void> task = new ScheduledTask<>(command);
140        deltaQueue.add(toTicks(delay, unit), task);
141        return task;
142    }
143
144    @Override
145    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
146        ScheduledTask<V> task = new ScheduledTask<V>(callable);
147        deltaQueue.add(toTicks(delay, unit), task);
148        return task;
149    }
150
151    @Override
152    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
153        return scheduleWithFixedDelay(command, initialDelay, period, unit);
154    }
155
156    @Override
157    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
158        ScheduledTask<Object> task = new ScheduledTask<>(toTicks(delay, unit), command);
159        deltaQueue.add(toTicks(initialDelay, unit), task);
160        return task;
161    }
162
163    @Override
164    public boolean awaitTermination(long _timeout, TimeUnit _unit) {
165        throw blockingOperationsNotSupported();
166    }
167
168    @Override
169    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> _tasks) {
170        throw blockingOperationsNotSupported();
171    }
172
173    @Override
174    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> _tasks, long _timeout, TimeUnit _unit)
175            throws InterruptedException {
176        throw blockingOperationsNotSupported();
177    }
178
179    @Override
180    public <T> T invokeAny(Collection<? extends Callable<T>> _tasks) {
181        throw blockingOperationsNotSupported();
182    }
183
184    @Override
185    public <T> T invokeAny(Collection<? extends Callable<T>> _tasks, long _timeout, TimeUnit _unit) {
186        throw blockingOperationsNotSupported();
187    }
188
189    @Override
190    public boolean isShutdown() {
191        throw shutdownNotSupported();
192    }
193
194    @Override
195    public boolean isTerminated() {
196        throw shutdownNotSupported();
197    }
198
199    @Override
200    public void shutdown() {
201        throw shutdownNotSupported();
202    }
203
204    @Override
205    public List<Runnable> shutdownNow() {
206        throw shutdownNotSupported();
207    }
208
209    @Override
210    public <T> Future<T> submit(Callable<T> callable) {
211        return schedule(callable, 0, TimeUnit.SECONDS);
212    }
213
214    @Override
215    public Future<?> submit(Runnable command) {
216        return submit(command, null);
217    }
218
219    @Override
220    public <T> Future<T> submit(Runnable command, T result) {
221        return submit(new CallableRunnableAdapter<T>(command, result));
222    }
223
224    private static final class CallableRunnableAdapter<T> implements Callable<T> {
225        private final Runnable runnable;
226        private final T result;
227
228        CallableRunnableAdapter(Runnable runnable, T result) {
229            this.runnable = runnable;
230            this.result = result;
231        }
232
233        @Override
234        public String toString() {
235            return runnable.toString();
236        }
237
238        @Override
239        public T call() {
240            runnable.run();
241            return result;
242        }
243    }
244
245    private final class ScheduledTask<T> implements ScheduledFuture<T>, Runnable {
246        private final long repeatDelay;
247        private final Callable<T> command;
248        private boolean isCancelled = false;
249        private boolean isDone = false;
250        private T futureResult;
251        private Exception failure = null;
252
253        ScheduledTask(Callable<T> command) {
254            this.repeatDelay = -1;
255            this.command = command;
256        }
257
258        ScheduledTask(Runnable command) {
259            this(-1, command);
260        }
261
262        ScheduledTask(long repeatDelay, Runnable command) {
263            this.repeatDelay = repeatDelay;
264            this.command = new CallableRunnableAdapter<T>(command, null);
265        }
266
267        @Override
268        public String toString() {
269            return command.toString() + " repeatDelay=" + repeatDelay;
270        }
271
272        public boolean repeats() {
273            return repeatDelay >= 0;
274        }
275
276        @Override
277        public long getDelay(TimeUnit unit) {
278            return unit.convert(Duration.ofNanos(deltaQueue.delay(this)));
279        }
280
281        @Override
282        public int compareTo(Delayed _object) {
283            throw new UnsupportedOperationException("not supported");
284        }
285
286        @Override
287        public boolean cancel(boolean _mayInterruptIfRunning) {
288            isCancelled = true;
289            return deltaQueue.remove(this);
290        }
291
292        @Override
293        public T get() throws ExecutionException {
294            if (!isDone) {
295                throw blockingOperationsNotSupported();
296            }
297
298            if (failure != null) {
299                throw new ExecutionException(failure);
300            }
301
302            return futureResult;
303        }
304
305        @Override
306        public T get(long _timeout, TimeUnit _unit) throws InterruptedException, ExecutionException, TimeoutException {
307            return get();
308        }
309
310        @Override
311        public boolean isCancelled() {
312            return isCancelled;
313        }
314
315        @Override
316        public boolean isDone() {
317            return isDone;
318        }
319
320        @Override
321        public void run() {
322            try {
323                futureResult = command.call();
324            } catch (Exception e) {
325                failure = e;
326            }
327            isDone = true;
328        }
329    }
330
331    private long toTicks(long duration, TimeUnit timeUnit) {
332        return TimeUnit.NANOSECONDS.convert(duration, timeUnit);
333    }
334
335    private UnsupportedSynchronousOperationException blockingOperationsNotSupported() {
336        return new UnsupportedSynchronousOperationException("cannot perform blocking wait on a task scheduled on a "
337                + NanosecondPrecisionDeterministicScheduler.class.getName());
338    }
339
340    private UnsupportedOperationException shutdownNotSupported() {
341        return new UnsupportedOperationException("shutdown not supported");
342    }
343}
344
Full Screen
copy
1package org.jmock.test.unit.lib.concurrent.internal;
2
3import org.jmock.lib.concurrent.internal.DeltaQueue;
4
5import junit.framework.TestCase;
6
7
8public class DeltaQueueTests extends TestCase {
9    DeltaQueue<String> deltaQueue = new DeltaQueue<String>();
10    
11    String elementA = "a";
12    String elementB = "b";
13    String elementC = "c";
14    
15    
16    public void testIsCreatedEmpty() {
17        assertTrue("is empty", deltaQueue.isEmpty());
18    }
19    
20    public void testCanScheduleAnElement() {
21        final long delay = 10L;
22        
23        deltaQueue.add(delay, elementA);
24        
25        assertTrue("is not empty", !deltaQueue.isEmpty());
26        
27        assertSame("next", elementA, deltaQueue.next());
28        assertEquals("delay", delay, deltaQueue.delay());
29    }
30    
31    public void testTicksDownTimeUntilScheduledElement() {
32        deltaQueue.add(10L, elementA);
33        
34        assertEquals(0L, deltaQueue.tick(1L));
35        
36        assertSame("next", elementA, deltaQueue.next());
37        assertEquals("delay", 9L, deltaQueue.delay());
38        
39        assertEquals(0L, deltaQueue.tick(4L));
40        assertSame("next", elementA, deltaQueue.next());
41        assertEquals("delay", 5L, deltaQueue.delay());
42        
43        assertEquals(0L, deltaQueue.tick(4L));
44        assertSame("next", elementA, deltaQueue.next());
45        assertEquals("delay", 1L, deltaQueue.delay());
46
47        assertEquals(0L, deltaQueue.tick(1L));
48        assertSame("next", elementA, deltaQueue.next());
49        assertEquals("delay", 0L, deltaQueue.delay());
50    }
51    
52    public void testReturnsTimeAfterElementIfTickGreaterThanDelay() {
53        deltaQueue.add(10L, elementA);
54        
55        assertEquals(5L, deltaQueue.tick(15L));
56        assertSame("next", elementA, deltaQueue.next());
57        assertEquals("delay", 0L, deltaQueue.delay());
58    }
59    
60    public void testCanPopElementWhenDelayIsZero() {
61        deltaQueue.add(10L, elementA);
62        
63        deltaQueue.tick(10L);
64        assertSame("popped", elementA, deltaQueue.pop());
65        assertTrue("is empty", deltaQueue.isEmpty());
66    }
67    
68    public void testCanScheduleMultipleElementsInAnyOrder() {
69        deltaQueue.add(10L, elementB);
70        deltaQueue.add(5L, elementA);
71        deltaQueue.add(12L, elementC);
72        
73        assertSame("next", elementA, deltaQueue.next());
74        assertEquals("delay", 5L, deltaQueue.delay());
75        
76        deltaQueue.tick(5L);
77        assertSame("popped A", elementA, deltaQueue.pop());
78        
79        assertSame("next", elementB, deltaQueue.next());
80        assertEquals("delay", 5L, deltaQueue.delay());
81        
82        deltaQueue.tick(5L);
83        assertSame("popped B", elementB, deltaQueue.pop());
84        
85        assertSame("next", elementC, deltaQueue.next());
86        assertEquals("delay", 2L, deltaQueue.delay());
87        
88        deltaQueue.tick(2L);
89        assertSame("popped C", elementC, deltaQueue.pop());
90        
91        assertTrue("is empty", deltaQueue.isEmpty());
92    }
93    
94    public void testReportsScheduleAsString() {
95        deltaQueue.add(10L, elementB);
96        deltaQueue.add(5L, elementA);
97        deltaQueue.add(12L, elementC);
98        
99        assertEquals("DeltaQueue[+5: a, +5: b, +2: c]", deltaQueue.toString());
100    }
101    
102    public void testTickingDownAnEmptyDeltaQueueDoesNothingButConsumesAllOfTheTickedTime() {
103        assertEquals(0L, deltaQueue.tick(1L));
104        assertEquals(0L, deltaQueue.tick(2L));
105        assertEquals(0L, deltaQueue.tick(19L));
106    }
107    
108    public void testElementsScheduledWithSameDelayAreExecutedInTheOrderThatTheyWereScheduled() {
109        deltaQueue.add(1L, elementA);
110        deltaQueue.add(1L, elementB);
111        deltaQueue.add(1L, elementC);
112        
113        deltaQueue.tick(1L);
114        
115        assertSame(elementA, deltaQueue.pop());
116        assertSame(elementB, deltaQueue.pop());
117        assertSame(elementC, deltaQueue.pop());
118    }
119    
120    public void testCanRemoveScheduledElements() {
121        deltaQueue.add(1L, elementA);
122        deltaQueue.add(2L, elementB);
123        deltaQueue.add(3L, elementC);
124        
125        assertTrue(deltaQueue.remove(elementB));
126        
127        deltaQueue.tick(1L);
128        assertSame(elementA, deltaQueue.pop());
129        
130        deltaQueue.tick(2L);
131        assertSame(elementC, deltaQueue.pop());
132    }
133    
134    public void testCanRemoveHead() {
135        deltaQueue.add(1L, elementA);
136        deltaQueue.add(2L, elementB);
137        deltaQueue.add(3L, elementC);
138        
139        deltaQueue.remove(elementA);
140        
141        deltaQueue.tick(2L);
142        assertSame(elementB, deltaQueue.pop());
143        
144        deltaQueue.tick(1L);
145        assertSame(elementC, deltaQueue.pop());
146    }
147    
148    public void testCanRemoveTail() {
149        deltaQueue.add(1L, elementA);
150        deltaQueue.add(2L, elementB);
151        deltaQueue.add(3L, elementC);
152       
153        deltaQueue.remove(elementC);
154        
155        deltaQueue.tick(1L);
156        assertSame(elementA, deltaQueue.pop());
157        
158        deltaQueue.tick(1L);
159        assertSame(elementB, deltaQueue.pop());
160        
161        assertTrue("is empty", deltaQueue.isEmpty());
162    }
163    
164    public void testReturnsFalseIfElementAlreadyRemoved() {
165        deltaQueue.add(1L, elementA);
166        deltaQueue.add(2L, elementB);
167        
168        assertFalse(deltaQueue.remove(elementC));
169    }
170}
171
Full Screen
copy
1package org.jmock.lib.concurrent;
2
3import java.util.Collection;
4import java.util.List;
5import java.util.concurrent.Callable;
6import java.util.concurrent.Delayed;
7import java.util.concurrent.ExecutionException;
8import java.util.concurrent.Executor;
9import java.util.concurrent.ExecutorService;
10import java.util.concurrent.Future;
11import java.util.concurrent.ScheduledExecutorService;
12import java.util.concurrent.ScheduledFuture;
13import java.util.concurrent.TimeUnit;
14import java.util.concurrent.TimeoutException;
15
16import org.jmock.lib.concurrent.internal.DeltaQueue;
17
18
19/**
20 * A {@link ScheduledExecutorService} that executes commands on the thread that calls
21 * {@link #runNextPendingCommand() runNextPendingCommand}, {@link #runUntilIdle() runUntilIdle} or 
22 * {@link #tick(long, TimeUnit) tick}.  Objects of this class can also be used
23 * as {@link Executor}s or {@link ExecutorService}s if you just want to control background execution 
24 * and don't need to schedule commands, but it may be simpler to use a {@link DeterministicExecutor}.
25 * 
26 * @author nat
27 */
28public class DeterministicScheduler implements ScheduledExecutorService {
29    private final DeltaQueue<ScheduledTask<?>> deltaQueue = new DeltaQueue<ScheduledTask<?>>();
30    
31    /**
32     * Runs time forwards by a given duration, executing any commands scheduled for
33     * execution during that time period, and any background tasks spawned by the 
34     * scheduled tasks.  Therefore, when a call to tick returns, the executor 
35     * will be idle.
36     * 
37     * @param duration
38     * @param timeUnit
39     */
40    public void tick(long duration, TimeUnit timeUnit) {
41        long remaining = toTicks(duration, timeUnit);
42        
43        do {
44            remaining = deltaQueue.tick(remaining);
45            runUntilIdle();
46            
47        } while (deltaQueue.isNotEmpty() && remaining > 0);
48    }
49    
50    /**
51     * Runs all commands scheduled to be executed immediately but does 
52     * not tick time forward.
53     */
54    public void runUntilIdle() {
55        while (!isIdle()) {
56            runNextPendingCommand();
57        }
58    }
59    
60    /**
61     * Runs the next command scheduled to be executed immediately.
62     */
63    public void runNextPendingCommand() {
64        ScheduledTask<?> scheduledTask = deltaQueue.pop();
65        
66        scheduledTask.run();
67        
68        if (scheduledTask.repeats()) {
69            deltaQueue.add(scheduledTask.repeatDelay, scheduledTask);
70        }
71    }
72    
73    /**
74     * Reports whether scheduler is "idle": has no commands pending immediate execution.
75     * 
76     * @return true if there are no commands pending immediate execution,
77     *         false if there are commands pending immediate execution.
78     */
79    public boolean isIdle() {
80        return deltaQueue.isEmpty() || deltaQueue.delay() > 0;
81    }
82    
83    public void execute(Runnable command) {
84        schedule(command, 0, TimeUnit.SECONDS);
85    }
86    
87    public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
88        ScheduledTask<Void> task = new ScheduledTask<Void>(command);
89        deltaQueue.add(toTicks(delay, unit), task);
90        return task;
91    }
92    
93    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
94        ScheduledTask<V> task = new ScheduledTask<V>(callable);
95        deltaQueue.add(toTicks(delay, unit), task);
96        return task;
97    }
98    
99    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
100        return scheduleWithFixedDelay(command, initialDelay, period, unit);
101    }
102    
103    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
104        ScheduledTask<Object> task = new ScheduledTask<Object>(toTicks(delay, unit), command);
105        deltaQueue.add(toTicks(initialDelay, unit), task);
106        return task;
107    }
108    
109    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
110        throw blockingOperationsNotSupported();
111    }
112
113    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
114        throw blockingOperationsNotSupported();
115    }
116
117    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException {
118        throw blockingOperationsNotSupported();
119    }
120    
121    public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
122        throws InterruptedException, ExecutionException 
123    {
124        throw blockingOperationsNotSupported();
125    }
126
127    public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) 
128        throws InterruptedException, ExecutionException, TimeoutException 
129    {
130        throw blockingOperationsNotSupported();
131    }
132
133    public boolean isShutdown() {
134        throw shutdownNotSupported();
135    }
136
137    public boolean isTerminated() {
138        throw shutdownNotSupported();
139    }
140
141    public void shutdown() {
142        throw shutdownNotSupported();
143    }
144
145    public List<Runnable> shutdownNow() {
146        throw shutdownNotSupported();
147    }
148    
149    public <T> Future<T> submit(Callable<T> callable) {
150        return schedule(callable, 0, TimeUnit.SECONDS);
151    }
152    
153    public Future<?> submit(Runnable command) {
154        return submit(command, null);
155    }
156    
157    public <T> Future<T> submit(Runnable command, T result) {
158        return submit(new CallableRunnableAdapter<T>(command, result));
159    }
160    
161    private final class CallableRunnableAdapter<T> implements Callable<T> {
162        private final Runnable runnable;
163        private final T result;
164        
165        public CallableRunnableAdapter(Runnable runnable, T result) {
166            this.runnable = runnable;
167            this.result = result;
168        }
169        
170        @Override
171        public String toString() {
172            return runnable.toString();
173        }
174
175        public T call() throws Exception {
176            runnable.run();
177            return result;
178        }
179    }
180    
181    private final class ScheduledTask<T> implements ScheduledFuture<T>, Runnable {
182        public final long repeatDelay;
183        public final Callable<T> command;
184        private boolean isCancelled = false;
185        private boolean isDone = false;
186        private T futureResult;
187        private Exception failure = null;
188        
189        public ScheduledTask(Callable<T> command) {
190            this.repeatDelay = -1;
191            this.command = command;
192        }
193        
194        public ScheduledTask(Runnable command) {
195            this(-1, command);
196        }
197        
198        public ScheduledTask(long repeatDelay, Runnable command) {
199            this.repeatDelay = repeatDelay;
200            this.command = new CallableRunnableAdapter<T>(command, null); 
201        }
202        
203        @Override
204        public String toString() {
205            return command.toString() + " repeatDelay=" + repeatDelay;
206        }
207        
208        public boolean repeats() {
209            return repeatDelay >= 0;
210        }
211
212        public long getDelay(TimeUnit unit) {
213            throw new UnsupportedOperationException("not supported");
214        }
215
216        public int compareTo(Delayed o) {
217            throw new UnsupportedOperationException("not supported");
218        }
219
220        public boolean cancel(boolean mayInterruptIfRunning) {
221            isCancelled = true;
222            return deltaQueue.remove(this);
223        }
224
225        public T get() throws InterruptedException, ExecutionException {
226            if (!isDone) {
227                throw blockingOperationsNotSupported();
228            }
229            
230            if (failure != null) {
231                throw new ExecutionException(failure);
232            }
233            
234            return futureResult;
235        }
236
237        public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
238            return get();
239        }
240        
241        public boolean isCancelled() {
242            return isCancelled;
243        }
244        
245        public boolean isDone() {
246            return isDone;
247        }
248
249        public void run() {
250            try {
251                futureResult = command.call();
252            }
253            catch (Exception e) {
254                failure = e;
255            }
256            isDone = true;
257        }
258    }
259
260    private long toTicks(long duration, TimeUnit timeUnit) {
261        return TimeUnit.MILLISECONDS.convert(duration, timeUnit);
262    }
263    
264    private UnsupportedSynchronousOperationException blockingOperationsNotSupported() {
265        return new UnsupportedSynchronousOperationException("cannot perform blocking wait on a task scheduled on a " + DeterministicScheduler.class.getName());
266    }
267    
268    private UnsupportedOperationException shutdownNotSupported() {
269        return new UnsupportedOperationException("shutdown not supported");
270    }
271}
272
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

...Most popular Stackoverflow questions on DeltaQueue

    No relevant questions found for this class 😞

Most used methods in DeltaQueue

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)