Skip to content

Commit

Permalink
use java.util.concurrent.locks.Condition instead of Thread.sleep()
Browse files Browse the repository at this point in the history
  • Loading branch information
webfolderio committed May 9, 2017
1 parent 2792ed9 commit d5faabf
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>io.webfolder</groupId>
<artifactId>cdp4j</artifactId>
<version>1.0.1</version>
<version>1.0.2</version>
<licenses>
<license>
<name>The MIT License</name>
Expand Down
24 changes: 18 additions & 6 deletions src/main/java/io/webfolder/cdp/session/Session.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
import static java.lang.Math.floor;
import static java.lang.String.format;
import static java.lang.String.valueOf;
import static java.lang.Thread.sleep;
import static java.lang.ThreadLocal.withInitial;
import static java.lang.reflect.Proxy.newProxyInstance;
import static java.util.Locale.ENGLISH;
Expand All @@ -45,6 +44,8 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Predicate;

import com.google.gson.Gson;
Expand Down Expand Up @@ -108,6 +109,8 @@ public class Session implements AutoCloseable,

private Command command;

private final ReentrantLock lock = new ReentrantLock(true);

private static final ThreadLocal<Boolean> ENABLE_ENTRY_EXIT_LOG =
withInitial(() -> { return TRUE; });

Expand Down Expand Up @@ -361,11 +364,20 @@ public byte[] captureScreenshot() {
}

public Session wait(int timeout) {
try {
logEntry("wait", timeout + "ms");
sleep(timeout);
} catch (InterruptedException e) {
throw new CdpException(e);
if ( lock.tryLock() ) {
Condition condition = lock.newCondition();
try {
logEntry("wait", timeout + "ms");
condition.await(timeout, MILLISECONDS);
} catch (InterruptedException e) {
throw new CdpException(e);
} finally {
if (lock.isLocked()) {
lock.unlock();
}
}
} else {
throw new CdpException("Unable to acquire lock");
}
return getThis();
}
Expand Down

0 comments on commit d5faabf

Please sign in to comment.