Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
OpLatch.java
Go to the documentation of this file.
1/*
2 * Copyright (c) 2015, the Dart project authors.
3 *
4 * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.eclipse.org/legal/epl-v10.html
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
12 * the License.
13 */
14package org.dartlang.vm.service;
15
16import java.util.concurrent.CountDownLatch;
17import java.util.concurrent.TimeUnit;
18
19/**
20 * {@link OpLatch} is used by one thread to wait for another thread to complete (see
21 * {@link OpLatch#waitOpComplete()} and {@link OpLatch#waitAndAssertOpComplete()}). If the operation
22 * does not complete before the expiration time then {@link OpLatch#waitOpComplete()} returns
23 * {@code false} and {@link OpLatch#waitAndAssertOpComplete()} throws an exception.
24 */
25class OpLatch {
26 final CountDownLatch latch = new CountDownLatch(1);
27 private long endTime;
28
29 /**
30 * Set or increase the time after which the operation is considered failed. This is automatically
31 * called by {@link #waitAndAssertOp()} and {@link #waitOpComplete()}.
32 */
33 public void opWorking() {
34 endTime = System.currentTimeMillis() + 5000;
35 }
36
37 /**
38 * Call to indicate that the operation completed successfully.
39 */
40 void opComplete() {
41 latch.countDown();
42 }
43
44 /**
45 * Wait for the operation to complete or the time limit to expire. Periodically call
46 * {@link #opWorking()} to increase the expiration time. Throw a {@link RuntimeException} if the
47 * operation did not complete before the expiration time.
48 */
50 if (!waitOpComplete()) {
51 System.out.println(">>> No response received");
52 throw new RuntimeException("No response received");
53 }
54 }
55
56 /**
57 * Wait for the operation to complete or the time limit to expire. Periodically call
58 * {@link #opWorking()} to increase the expiration time.
59 *
60 * @return {@code true} if the operation completed, or {@code false} otherwise
61 */
62 boolean waitOpComplete() {
63 opWorking();
64 while (true) {
65 long waitTimeMillis = endTime - System.currentTimeMillis();
66 if (waitTimeMillis <= 0) {
67 return latch.getCount() == 0;
68 }
69 try {
70 if (latch.await(waitTimeMillis, TimeUnit.MILLISECONDS)) {
71 return true;
72 }
73 } catch (InterruptedException e) {
74 // ignore and loop to check if timeout has changed
75 }
76 }
77 }
78}
final CountDownLatch latch
Definition OpLatch.java:26