BAEL-3287: Move implementations to test folder
This commit is contained in:
@@ -12,3 +12,4 @@ This module contains articles about core Java features that have been introduced
|
||||
- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api)
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
|
||||
- [Multi-Release JAR Files with Maven](https://www.baeldung.com/maven-multi-release-jars)
|
||||
|
||||
@@ -33,8 +33,104 @@
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${awaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>incubator-features</id>
|
||||
<build>
|
||||
<finalName>core-java-9-new-features</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
<compilerArgument>--add-modules=jdk.incubator.httpclient</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>--add-modules=jdk.incubator.httpclient</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>mrjar-generation</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>compile-java-8</id>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<compileSourceRoots>
|
||||
<compileSourceRoot>${project.basedir}/src/main/java8</compileSourceRoot>
|
||||
</compileSourceRoots>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>compile-java-9</id>
|
||||
<phase>compile</phase>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<release>9</release>
|
||||
<compileSourceRoots>
|
||||
<compileSourceRoot>${project.basedir}/src/main/java9</compileSourceRoot>
|
||||
</compileSourceRoots>
|
||||
<outputDirectory>${project.build.outputDirectory}/META-INF/versions/9</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>default-testCompile</id>
|
||||
<phase>test-compile</phase>
|
||||
<goals>
|
||||
<goal>testCompile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>${maven-jar-plugin.version}</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifestEntries>
|
||||
<Multi-Release>true</Multi-Release>
|
||||
</manifestEntries>
|
||||
<manifest>
|
||||
<mainClass>com.baeldung.multireleaseapp.App</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
<build>
|
||||
<finalName>core-java-9-new-features</finalName>
|
||||
<plugins>
|
||||
@@ -58,12 +154,14 @@
|
||||
</pluginRepositories>
|
||||
|
||||
<properties>
|
||||
<rxjava.version>3.0.0</rxjava.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<awaitility.version>4.0.2</awaitility.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
<rxjava.version>3.0.0</rxjava.version>
|
||||
<maven-jar-plugin.version>3.2.0</maven-jar-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
package com.baeldung.java9.streams.reactive.flowvsrx;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.SubmissionPublisher;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class FlowApiLiveVideo {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(FlowApiLiveVideo.class);
|
||||
|
||||
static class VideoPlayer implements Flow.Subscriber<VideoFrame> {
|
||||
Flow.Subscription subscription = null;
|
||||
|
||||
@Override
|
||||
public void onSubscribe(Flow.Subscription subscription) {
|
||||
this.subscription = subscription;
|
||||
subscription.request(1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(VideoFrame item) {
|
||||
log.info("play #{}", item.getNumber());
|
||||
sleep(30);
|
||||
subscription.request(1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable throwable) {
|
||||
log.error("There is an error in video streaming:{}", throwable.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
log.error("Video has ended");
|
||||
}
|
||||
}
|
||||
|
||||
static class VideoStreamServer extends SubmissionPublisher<VideoFrame> {
|
||||
public VideoStreamServer() {
|
||||
super(Executors.newSingleThreadExecutor(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void sleep(int i) {
|
||||
try {
|
||||
Thread.sleep(i);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
VideoStreamServer streamServer = new VideoStreamServer();
|
||||
streamServer.subscribe(new VideoPlayer());
|
||||
|
||||
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
|
||||
AtomicLong frameNumber = new AtomicLong();
|
||||
executor.scheduleWithFixedDelay(() -> {
|
||||
streamServer.offer(new VideoFrame(frameNumber.getAndIncrement()), (subscriber, videoFrame) -> {
|
||||
subscriber.onError(new RuntimeException("Frame#" + videoFrame.getNumber() + " droped because of back pressure"));
|
||||
return true;
|
||||
});
|
||||
}, 0, 1, TimeUnit.MILLISECONDS);
|
||||
|
||||
sleep(1000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.multireleaseapp;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class App {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(App.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
logger.info(String.format("Running on %s", new DefaultVersion().version()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.multireleaseapp;
|
||||
|
||||
public class DefaultVersion implements Version {
|
||||
|
||||
@Override
|
||||
public String version() {
|
||||
return System.getProperty("java.version");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.multireleaseapp;
|
||||
|
||||
interface Version {
|
||||
public String version();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.multireleaseapp;
|
||||
|
||||
public class DefaultVersion implements Version {
|
||||
|
||||
@Override
|
||||
public String version() {
|
||||
return Runtime.version().toString();
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat;
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
public class HttpClientTest {
|
||||
public class HttpClientIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
|
||||
@@ -55,7 +55,7 @@ public class HttpClientTest {
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
|
||||
assertThat(response.body(), containsString("https://stackoverflow.com/"));
|
||||
assertThat(response.body(), containsString(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -22,7 +22,7 @@ import static org.junit.Assert.assertThat;
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
public class HttpRequestTest {
|
||||
public class HttpRequestIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
||||
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertThat;
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
public class HttpResponseTest {
|
||||
public class HttpResponseIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
||||
@@ -5,10 +5,12 @@ import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.SubmissionPublisher;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.assertj.core.api.Java6Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
|
||||
public class ReactiveStreamsTest {
|
||||
public class ReactiveStreamsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenPublisher_whenSubscribeToIt_thenShouldConsumeAllElements() throws InterruptedException {
|
||||
@@ -25,7 +27,7 @@ public class ReactiveStreamsTest {
|
||||
|
||||
//then
|
||||
|
||||
await().atMost(1000, TimeUnit.MILLISECONDS).until(
|
||||
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
|
||||
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(items)
|
||||
);
|
||||
}
|
||||
@@ -46,7 +48,7 @@ public class ReactiveStreamsTest {
|
||||
publisher.close();
|
||||
|
||||
//then
|
||||
await().atMost(1000, TimeUnit.MILLISECONDS).until(
|
||||
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
|
||||
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expectedResult)
|
||||
);
|
||||
}
|
||||
@@ -66,7 +68,7 @@ public class ReactiveStreamsTest {
|
||||
publisher.close();
|
||||
|
||||
//then
|
||||
await().atMost(1000, TimeUnit.MILLISECONDS).until(
|
||||
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
|
||||
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expected)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.java9.streams.reactive.flowvsrx;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.SubmissionPublisher;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
public class FlowApiLiveVideo {
|
||||
|
||||
static class VideoPlayer implements Flow.Subscriber<VideoFrame> {
|
||||
Flow.Subscription subscription = null;
|
||||
private long consumerDelay = 30;
|
||||
|
||||
public VideoPlayer(long consumerDelay) {
|
||||
this.consumerDelay = consumerDelay;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSubscribe(Flow.Subscription subscription) {
|
||||
this.subscription = subscription;
|
||||
subscription.request(1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(VideoFrame item) {
|
||||
try {
|
||||
Thread.sleep(consumerDelay);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
subscription.request(1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable throwable) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
}
|
||||
|
||||
static class VideoStreamServer extends SubmissionPublisher<VideoFrame> {
|
||||
ScheduledExecutorService executor = null;
|
||||
|
||||
public VideoStreamServer(int bufferSize) {
|
||||
super(Executors.newSingleThreadExecutor(), bufferSize);
|
||||
executor = Executors.newScheduledThreadPool(1);
|
||||
}
|
||||
|
||||
void startStreaming(long produceDelay, Runnable onDrop) {
|
||||
AtomicLong frameNumber = new AtomicLong();
|
||||
executor.scheduleWithFixedDelay(() -> {
|
||||
offer(new VideoFrame(frameNumber.getAndIncrement()), (subscriber, videoFrame) -> {
|
||||
subscriber.onError(new RuntimeException("Frame#" + videoFrame.getNumber() + " dropped because of back pressure"));
|
||||
onDrop.run();
|
||||
return true;
|
||||
});
|
||||
}, 0, produceDelay, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
public static void streamLiveVideo(long produceDelay, long consumeDelay, int bufferSize, Runnable onError){
|
||||
FlowApiLiveVideo.VideoStreamServer streamServer = new FlowApiLiveVideo.VideoStreamServer(bufferSize);
|
||||
streamServer.subscribe(new FlowApiLiveVideo.VideoPlayer(consumeDelay));
|
||||
streamServer.startStreaming(produceDelay, onError);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.java9.streams.reactive.flowvsrx;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
|
||||
public class LiveVideoFlowVsRxUnitTest {
|
||||
|
||||
private final static long SLOW_CONSUMER_DELAY = 30;
|
||||
private final static long FAST_CONSUMER_DELAY = 1;
|
||||
private final static long PRODUCER_DELAY = 1;
|
||||
private final static int BUFFER_SIZE = 10;
|
||||
private final static long AWAIT = 1000;
|
||||
|
||||
@Test
|
||||
public void givenSlowVideoPlayer_whenSubscribedToFlowApiLiveVideo_thenExpectErrorOnBackPressure() {
|
||||
AtomicLong errors = new AtomicLong();
|
||||
|
||||
FlowApiLiveVideo.streamLiveVideo(PRODUCER_DELAY, SLOW_CONSUMER_DELAY, BUFFER_SIZE, errors::incrementAndGet);
|
||||
|
||||
await()
|
||||
.atMost(AWAIT, TimeUnit.MILLISECONDS)
|
||||
.untilAsserted(() -> Assertions.assertTrue(errors.get() > 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFastVideoPlayer_whenSubscribedToFlowApiLiveVideo_thenExpectNoErrorOnBackPressure() throws InterruptedException {
|
||||
AtomicLong errors = new AtomicLong();
|
||||
|
||||
FlowApiLiveVideo.streamLiveVideo(PRODUCER_DELAY, FAST_CONSUMER_DELAY, BUFFER_SIZE, errors::incrementAndGet);
|
||||
|
||||
Thread.sleep(AWAIT);
|
||||
Assertions.assertEquals(0, errors.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSlowVideoPlayer_whenSubscribedToRxJavaLiveVideo_thenExpectErrorOnBackPressure() {
|
||||
AtomicLong errors = new AtomicLong();
|
||||
|
||||
RxJavaLiveVideo.streamLiveVideo(PRODUCER_DELAY, SLOW_CONSUMER_DELAY, BUFFER_SIZE, errors::incrementAndGet);
|
||||
|
||||
await()
|
||||
.atMost(AWAIT, TimeUnit.MILLISECONDS)
|
||||
.untilAsserted(() -> Assertions.assertTrue(errors.get() > 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFastVideoPlayer_whenSubscribedToRxJavaLiveVideo_thenExpectNoErrorOnBackPressure() throws InterruptedException {
|
||||
AtomicLong errors = new AtomicLong();
|
||||
|
||||
RxJavaLiveVideo.streamLiveVideo(PRODUCER_DELAY, FAST_CONSUMER_DELAY, BUFFER_SIZE, errors::incrementAndGet);
|
||||
|
||||
Thread.sleep(AWAIT);
|
||||
Assertions.assertEquals(0, errors.get());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,37 +2,35 @@ package com.baeldung.java9.streams.reactive.flowvsrx;
|
||||
|
||||
import io.reactivex.rxjava3.core.BackpressureOverflowStrategy;
|
||||
import io.reactivex.rxjava3.core.Flowable;
|
||||
import io.reactivex.rxjava3.disposables.Disposable;
|
||||
import io.reactivex.rxjava3.schedulers.Schedulers;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.stream.Stream;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class RxJavaLiveVideo {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(RxJavaLiveVideo.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
Flowable
|
||||
public static Disposable streamLiveVideo(long produceDelay, long consumeDelay, int bufferSize, Runnable onError) {
|
||||
return Flowable
|
||||
.fromStream(Stream.iterate(new VideoFrame(0), videoFrame -> {
|
||||
sleep(1);
|
||||
sleep(produceDelay);
|
||||
return new VideoFrame(videoFrame.getNumber() + 1);
|
||||
}))
|
||||
.onBackpressureBuffer(10, null, BackpressureOverflowStrategy.ERROR)
|
||||
.subscribeOn(Schedulers.from(Executors.newSingleThreadScheduledExecutor()), true)
|
||||
.onBackpressureBuffer(bufferSize, null, BackpressureOverflowStrategy.ERROR)
|
||||
.observeOn(Schedulers.from(Executors.newSingleThreadExecutor()))
|
||||
.doOnError(Throwable::printStackTrace)
|
||||
.subscribe(item -> {
|
||||
log.info("play #" + item.getNumber());
|
||||
sleep(30);
|
||||
sleep(consumeDelay);
|
||||
}, throwable -> {
|
||||
onError.run();
|
||||
});
|
||||
}
|
||||
|
||||
private static void sleep(int i) {
|
||||
private static void sleep(long i) {
|
||||
try {
|
||||
Thread.sleep(i);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
package com.baeldung.java9.varhandles;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class VariableHandlesTest {
|
||||
|
||||
public int publicTestVariable = 1;
|
||||
private int privateTestVariable = 1;
|
||||
public int variableToSet = 1;
|
||||
public int variableToCompareAndSet = 1;
|
||||
public int variableToGetAndAdd = 0;
|
||||
public byte variableToBitwiseOr = 0;
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
|
||||
|
||||
assertThat(publicIntHandle.coordinateTypes().size() == 1);
|
||||
assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandles.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle privateIntHandle = MethodHandles
|
||||
.privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup())
|
||||
.findVarHandle(VariableHandlesTest.class, "privateTestVariable", int.class);
|
||||
|
||||
assertThat(privateIntHandle.coordinateTypes().size() == 1);
|
||||
assertThat(privateIntHandle.coordinateTypes().get(0) == VariableHandlesTest.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle arrayVarHandle = MethodHandles
|
||||
.arrayElementVarHandle(int[].class);
|
||||
|
||||
assertThat(arrayVarHandle.coordinateTypes().size() == 2);
|
||||
assertThat(arrayVarHandle.coordinateTypes().get(0) == int[].class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
|
||||
|
||||
assertThat((int) publicIntHandle.get(this) == 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "variableToSet", int.class);
|
||||
publicIntHandle.set(this, 15);
|
||||
|
||||
assertThat((int) publicIntHandle.get(this) == 15);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "variableToCompareAndSet", int.class);
|
||||
publicIntHandle.compareAndSet(this, 1, 100);
|
||||
|
||||
assertThat((int) publicIntHandle.get(this) == 100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "variableToGetAndAdd", int.class);
|
||||
int before = (int) publicIntHandle.getAndAdd(this, 200);
|
||||
|
||||
assertThat(before == 0);
|
||||
assertThat((int) publicIntHandle.get(this) == 200);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "variableToBitwiseOr", byte.class);
|
||||
byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127);
|
||||
|
||||
assertThat(before == 0);
|
||||
assertThat(variableToBitwiseOr == 127);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.baeldung.java9.varhandles;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class VariableHandlesUnitTest {
|
||||
|
||||
public int publicTestVariable = 1;
|
||||
private int privateTestVariable = 1;
|
||||
public int variableToSet = 1;
|
||||
public int variableToCompareAndSet = 1;
|
||||
public int variableToGetAndAdd = 0;
|
||||
public byte variableToBitwiseOr = 0;
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle PUBLIC_TEST_VARIABLE = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesUnitTest.class)
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "publicTestVariable", int.class);
|
||||
|
||||
assertEquals(1, PUBLIC_TEST_VARIABLE.coordinateTypes().size());
|
||||
assertEquals(VariableHandlesUnitTest.class, PUBLIC_TEST_VARIABLE.coordinateTypes().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle PRIVATE_TEST_VARIABLE = MethodHandles
|
||||
.privateLookupIn(VariableHandlesUnitTest.class, MethodHandles.lookup())
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "privateTestVariable", int.class);
|
||||
|
||||
assertEquals(1, PRIVATE_TEST_VARIABLE.coordinateTypes().size());
|
||||
assertEquals(VariableHandlesUnitTest.class, PRIVATE_TEST_VARIABLE.coordinateTypes().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle arrayVarHandle = MethodHandles
|
||||
.arrayElementVarHandle(int[].class);
|
||||
|
||||
assertEquals(2, arrayVarHandle.coordinateTypes().size());
|
||||
assertEquals(int[].class, arrayVarHandle.coordinateTypes().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle PUBLIC_TEST_VARIABLE = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesUnitTest.class)
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "publicTestVariable", int.class);
|
||||
|
||||
assertEquals(1, (int) PUBLIC_TEST_VARIABLE.get(this));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle VARIABLE_TO_SET = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesUnitTest.class)
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "variableToSet", int.class);
|
||||
|
||||
VARIABLE_TO_SET.set(this, 15);
|
||||
assertEquals(15, (int) VARIABLE_TO_SET.get(this));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle VARIABLE_TO_COMPARE_AND_SET = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesUnitTest.class)
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "variableToCompareAndSet", int.class);
|
||||
|
||||
VARIABLE_TO_COMPARE_AND_SET.compareAndSet(this, 1, 100);
|
||||
assertEquals(100, (int) VARIABLE_TO_COMPARE_AND_SET.get(this));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle VARIABLE_TO_GET_AND_ADD = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesUnitTest.class)
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "variableToGetAndAdd", int.class);
|
||||
|
||||
int before = (int) VARIABLE_TO_GET_AND_ADD.getAndAdd(this, 200);
|
||||
|
||||
assertEquals(0, before);
|
||||
assertEquals(200, (int) VARIABLE_TO_GET_AND_ADD.get(this));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle VARIABLE_TO_BITWISE_OR = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesUnitTest.class)
|
||||
.findVarHandle(VariableHandlesUnitTest.class, "variableToBitwiseOr", byte.class);
|
||||
byte before = (byte) VARIABLE_TO_BITWISE_OR.getAndBitwiseOr(this, (byte) 127);
|
||||
|
||||
assertEquals(0, before);
|
||||
assertEquals(127, (byte) VARIABLE_TO_BITWISE_OR.get(this));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user