parent
ec90772372
commit
5d6e1a21ff
|
@ -0,0 +1,36 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-concurrency-advanced-5</artifactId>
|
||||
<name>core-java-concurrency-advanced-5</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-concurrency-advanced-5</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.wait_synchronization;
|
||||
|
||||
public class ConditionChecker {
|
||||
|
||||
private volatile Boolean jobIsDone;
|
||||
private final Object lock = new Object();
|
||||
|
||||
public void ensureCondition() {
|
||||
synchronized (lock) {
|
||||
while (!jobIsDone) {
|
||||
try {
|
||||
lock.wait();
|
||||
} catch (InterruptedException e) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void complete() {
|
||||
synchronized (lock) {
|
||||
jobIsDone = true;
|
||||
lock.notify();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.wait_synchronization;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ConditionCheckerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBothMethodsAreSynchronized_whenBothMethodsAreCalled_thenNoExceptionsOrDeadlocks() {
|
||||
ConditionChecker conditionChecker = new ConditionChecker();
|
||||
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
|
||||
Assertions.assertThatCode(() -> {
|
||||
executorService.submit(conditionChecker::ensureCondition);
|
||||
executorService.submit(conditionChecker::complete);
|
||||
}).doesNotThrowAnyException();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue