Revert "BAEL-4134"
This commit is contained in:
committed by
GitHub
parent
4a35b97bad
commit
7ab2f437ee
@@ -9,3 +9,4 @@ This module contains articles about Java 14.
|
||||
- [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof)
|
||||
- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception)
|
||||
- [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access)
|
||||
- [Java 14 Record Keyword](https://www.baeldung.com/java-record-keyword)
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-8-datetime-2</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-8-datetime</name>
|
||||
<name>core-java-8-datetime-2</name>
|
||||
<packaging>jar</packaging>
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
|
||||
@@ -5,7 +5,7 @@ This module contains articles about the improvements to core Java features intro
|
||||
### Relevant Articles:
|
||||
|
||||
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
|
||||
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
|
||||
- [Java Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
|
||||
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
|
||||
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
|
||||
- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture)
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>apache.snapshots</id>
|
||||
<url>http://repository.apache.org/snapshots/</url>
|
||||
<url>https://repository.apache.org/snapshots/</url>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
|
||||
@@ -16,6 +16,11 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.reactivex.rxjava3</groupId>
|
||||
<artifactId>rxjava</artifactId>
|
||||
<version>${rxjava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
@@ -144,11 +149,12 @@
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>apache.snapshots</id>
|
||||
<url>http://repository.apache.org/snapshots/</url>
|
||||
<url>https://repository.apache.org/snapshots/</url>
|
||||
</pluginRepository>
|
||||
</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>
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.java9.currentmethod;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CurrentExecutingMethodUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenJava9_whenWalkingTheStack_thenFindMethod() {
|
||||
StackWalker walker = StackWalker.getInstance();
|
||||
Optional<String> methodName = walker.walk(frames -> frames
|
||||
.findFirst()
|
||||
.map(StackWalker.StackFrame::getMethodName)
|
||||
);
|
||||
|
||||
assertTrue(methodName.isPresent());
|
||||
assertEquals("givenJava9_whenWalkingTheStack_thenFindMethod", methodName.get());
|
||||
}
|
||||
}
|
||||
+71
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+61
@@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
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;
|
||||
|
||||
public class RxJavaLiveVideo {
|
||||
|
||||
public static Disposable streamLiveVideo(long produceDelay, long consumeDelay, int bufferSize, Runnable onError) {
|
||||
return Flowable
|
||||
.fromStream(Stream.iterate(new VideoFrame(0), videoFrame -> {
|
||||
sleep(produceDelay);
|
||||
return new VideoFrame(videoFrame.getNumber() + 1);
|
||||
}))
|
||||
.subscribeOn(Schedulers.from(Executors.newSingleThreadScheduledExecutor()), true)
|
||||
.onBackpressureBuffer(bufferSize, null, BackpressureOverflowStrategy.ERROR)
|
||||
.observeOn(Schedulers.from(Executors.newSingleThreadExecutor()))
|
||||
.subscribe(item -> {
|
||||
sleep(consumeDelay);
|
||||
}, throwable -> {
|
||||
onError.run();
|
||||
});
|
||||
}
|
||||
|
||||
private static void sleep(long i) {
|
||||
try {
|
||||
Thread.sleep(i);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.java9.streams.reactive.flowvsrx;
|
||||
|
||||
class VideoFrame {
|
||||
private long number;
|
||||
|
||||
public VideoFrame(long number) {
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public long getNumber() {
|
||||
return number;
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>apache.snapshots</id>
|
||||
<url>http://repository.apache.org/snapshots/</url>
|
||||
<url>https://repository.apache.org/snapshots/</url>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package com.baeldung.java9.inputstream.outputstream;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.io.ByteStreams;
|
||||
|
||||
public class InputStreamToOutputStreamUnitTest {
|
||||
|
||||
/**
|
||||
* Reads all bytes from an input stream and writes them to an output stream.
|
||||
* @param source - input stream to copy data from
|
||||
* @param target - output stream to copy data too
|
||||
*/
|
||||
void copy(InputStream source, OutputStream target) throws IOException {
|
||||
byte[] buf = new byte[8192];
|
||||
int length;
|
||||
while ((length = source.read(buf)) > 0) {
|
||||
target.write(buf, 0, length);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJavaEight_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException {
|
||||
String initialString = "Hello World!";
|
||||
|
||||
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
|
||||
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
|
||||
copy(inputStream, targetStream);
|
||||
|
||||
assertEquals(initialString, new String(targetStream.toByteArray()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJavaEight_whenCopyingLongInputStreamToOutputStream_thenCorrect() throws IOException {
|
||||
String initialString = randomAlphabetic(20480);
|
||||
|
||||
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
|
||||
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
|
||||
copy(inputStream, targetStream);
|
||||
|
||||
assertEquals(initialString, new String(targetStream.toByteArray()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJavaNine_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException {
|
||||
String initialString = "Hello World!";
|
||||
|
||||
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
|
||||
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
|
||||
inputStream.transferTo(targetStream);
|
||||
|
||||
assertEquals(initialString, new String(targetStream.toByteArray()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException {
|
||||
String initialString = "Hello World!";
|
||||
|
||||
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
|
||||
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
|
||||
ByteStreams.copy(inputStream, targetStream);
|
||||
|
||||
assertEquals(initialString, new String(targetStream.toByteArray()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException {
|
||||
String initialString = "Hello World!";
|
||||
|
||||
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
|
||||
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
|
||||
IOUtils.copy(inputStream, targetStream);
|
||||
|
||||
assertEquals(initialString, new String(targetStream.toByteArray()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,4 +4,5 @@ This module contains complete guides about arrays in Java
|
||||
|
||||
### Relevant Articles:
|
||||
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
|
||||
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
|
||||
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
|
||||
- [What is [Ljava.lang.Object;?]](https://www.baeldung.com/java-tostring-array)
|
||||
|
||||
@@ -13,32 +13,6 @@
|
||||
<name>core-java-arrays-operations-basic</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${shade.plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<finalName>benchmarks</finalName>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.openjdk.jmh.Main</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
@@ -66,6 +40,32 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${shade.plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<finalName>benchmarks</finalName>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.openjdk.jmh.Main</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<shade.plugin.version>3.2.0</shade.plugin.version>
|
||||
|
||||
|
||||
@@ -14,32 +14,6 @@
|
||||
<name>core-java-arrays-sorting</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${shade.plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<finalName>benchmarks</finalName>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.openjdk.jmh.Main</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<!-- Utilities -->
|
||||
<dependency>
|
||||
@@ -74,6 +48,32 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${shade.plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<finalName>benchmarks</finalName>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.openjdk.jmh.Main</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<shade.plugin.version>3.2.0</shade.plugin.version>
|
||||
|
||||
|
||||
@@ -19,31 +19,31 @@
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13</version>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.googlecode.thread-weaver</groupId>
|
||||
<artifactId>threadweaver</artifactId>
|
||||
<version>0.2</version>
|
||||
<version>${threadweaver.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.tempus-fugit</groupId>
|
||||
<artifactId>tempus-fugit</artifactId>
|
||||
<version>1.1</version>
|
||||
<version>${tempus-fugit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.googlecode.multithreadedtc</groupId>
|
||||
<artifactId>multithreadedtc</artifactId>
|
||||
<version>1.01</version>
|
||||
<version>${multithreadedtc.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jcstress</groupId>
|
||||
<artifactId>jcstress-core</artifactId>
|
||||
<version>0.5</version>
|
||||
<version>${jcstress-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -63,8 +63,8 @@
|
||||
<version>3.1</version>
|
||||
<configuration>
|
||||
<compilerVersion>${javac.target}</compilerVersion>
|
||||
<source>${javac.target}</source>
|
||||
<target>${javac.target}</target>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
@@ -99,7 +99,11 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<javac.target>1.8</javac.target>
|
||||
<junit.version>4.13</junit.version>
|
||||
<threadweaver.version>0.2</threadweaver.version>
|
||||
<tempus-fugit.version>1.1</tempus-fugit.version>
|
||||
<multithreadedtc.version>1.01</multithreadedtc.version>
|
||||
<jcstress-core.version>0.5</jcstress-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -13,4 +13,6 @@ This module contains articles about advanced topics about multithreading with co
|
||||
- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock)
|
||||
- [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference)
|
||||
- [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency)
|
||||
- [Introduction to Lock-Free Data Structures](https://www.baeldung.com/lock-free-programming)
|
||||
- [Introduction to Exchanger in Java](https://www.baeldung.com/java-exchanger)
|
||||
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.thisescape;
|
||||
|
||||
public class ImplicitEscape {
|
||||
|
||||
public ImplicitEscape() {
|
||||
Thread t = new Thread() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("Started...");
|
||||
}
|
||||
};
|
||||
|
||||
t.start();
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.thisescape;
|
||||
|
||||
public class LoggerRunnable implements Runnable {
|
||||
|
||||
public LoggerRunnable() {
|
||||
Thread thread = new Thread(this); // this escapes
|
||||
thread.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("Started...");
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.thisescape;
|
||||
|
||||
public class SafePublication implements Runnable {
|
||||
|
||||
private final Thread thread;
|
||||
|
||||
public SafePublication() {
|
||||
thread = new Thread(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("Started...");
|
||||
}
|
||||
|
||||
public void start() {
|
||||
thread.start();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SafePublication publication = new SafePublication();
|
||||
publication.start();
|
||||
}
|
||||
}
|
||||
+16
@@ -34,4 +34,20 @@ public class BaeldungSychronizedBlockUnitTest {
|
||||
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHoldingTheLock_whenReentrant_thenCanAcquireItAgain() {
|
||||
Object lock = new Object();
|
||||
synchronized (lock) {
|
||||
System.out.println("First time acquiring it");
|
||||
|
||||
synchronized (lock) {
|
||||
System.out.println("Entering again");
|
||||
|
||||
synchronized (lock) {
|
||||
System.out.println("And again");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -13,3 +13,4 @@ This module contains articles about concurrent Java collections
|
||||
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
|
||||
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
|
||||
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
|
||||
- [LinkedBlockingQueue vs ConcurrentLinkedQueue](https://www.baeldung.com/java-queue-linkedblocking-concurrentlinked)
|
||||
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.weeknumber;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
public class WeekNumberUsingCalendar {
|
||||
|
||||
public int getWeekNumberFrom(String day, String dateFormat, Locale locale) throws ParseException {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
|
||||
|
||||
Calendar calendar = Calendar.getInstance(locale);
|
||||
Date date = sdf.parse(day);
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.WEEK_OF_YEAR);
|
||||
}
|
||||
|
||||
public int getWeekNumberFrom(int year, int month, int day, Locale locale) {
|
||||
Calendar calendar = Calendar.getInstance(locale);
|
||||
calendar.set(year, month, day);
|
||||
|
||||
return calendar.get(Calendar.WEEK_OF_YEAR);
|
||||
}
|
||||
|
||||
public int getWeekNumberFrom(int year, int month, int day, int firstDayOfWeek, int minimalDaysInFirstWeek, Locale locale) {
|
||||
Calendar calendar = Calendar.getInstance(locale);
|
||||
calendar.setFirstDayOfWeek(firstDayOfWeek);
|
||||
calendar.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek);
|
||||
calendar.set(year, month, day);
|
||||
|
||||
return calendar.get(Calendar.WEEK_OF_YEAR);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
|
||||
System.out.println(calendar.getWeekNumberFrom(2020, 2, 22, Locale.CANADA));
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package com.baeldung.weeknumber;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoField;
|
||||
import java.time.temporal.WeekFields;
|
||||
import java.util.Locale;
|
||||
|
||||
public class WeekNumberUsingLocalDate {
|
||||
|
||||
public Integer getWeekNumberUsingWeekFiedsFrom(String day, String dayFormat, Locale locale) {
|
||||
LocalDate date = LocalDate.parse(day, DateTimeFormatter.ofPattern(dayFormat));
|
||||
|
||||
return date.get(WeekFields.of(locale)
|
||||
.weekOfYear());
|
||||
}
|
||||
|
||||
public Integer getWeekNumberUsinWeekFieldsFrom(int year, int month, int day, Locale locale) {
|
||||
LocalDate date = LocalDate.of(year, month, day);
|
||||
|
||||
return date.get(WeekFields.of(locale)
|
||||
.weekOfYear());
|
||||
}
|
||||
|
||||
public Integer getWeekNumberUsingChronoFieldFrom(int year, int month, int day) {
|
||||
LocalDate date = LocalDate.of(year, month, day);
|
||||
|
||||
return date.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.weeknumber;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.ChronoField;
|
||||
import java.time.temporal.WeekFields;
|
||||
import java.util.Calendar;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class GetWeekNumberUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDateUsingFieldsAndLocaleItaly_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
|
||||
Calendar calendar = Calendar.getInstance(Locale.ITALY);
|
||||
calendar.set(2020, 10, 22);
|
||||
|
||||
assertEquals(47, calendar.get(Calendar.WEEK_OF_YEAR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateUsingFieldsAndLocaleCanada_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
|
||||
Calendar calendar = Calendar.getInstance(Locale.CANADA);
|
||||
calendar.set(2020, 10, 22);
|
||||
|
||||
assertEquals(48, calendar.get(Calendar.WEEK_OF_YEAR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateUsingFieldsAndLocaleItaly_whenChangingWeekCalcSettings_thenWeekIsReturnedCorrectly() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setFirstDayOfWeek(Calendar.SUNDAY);
|
||||
calendar.setMinimalDaysInFirstWeek(4);
|
||||
calendar.set(2020, 2, 22);
|
||||
|
||||
assertEquals(13, calendar.get(Calendar.WEEK_OF_YEAR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateUsingChronoFields_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
|
||||
LocalDate date = LocalDate.of(2020, 3, 22);
|
||||
|
||||
assertEquals(12, date.get(ChronoField.ALIGNED_WEEK_OF_YEAR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateUsingFieldsWithLocaleItaly_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
|
||||
LocalDate date = LocalDate.of(2020, 3, 22);
|
||||
|
||||
assertEquals(12, date.get(WeekFields.of(Locale.ITALY)
|
||||
.weekOfYear()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateUsingFieldsWithLocaleCanada_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
|
||||
LocalDate date = LocalDate.of(2020, 3, 22);
|
||||
|
||||
assertEquals(13, date.get(WeekFields.of(Locale.CANADA)
|
||||
.weekOfYear()));
|
||||
}
|
||||
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
package com.baeldung.weeknumber;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.Calendar;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class WeekNumberUsingCalendarUnitTest {
|
||||
@Test
|
||||
public void givenDateInStringAndDateFormatUsingLocaleItaly_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() throws ParseException {
|
||||
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
|
||||
|
||||
assertEquals(12, calendar.getWeekNumberFrom("20200322", "yyyyMMdd", Locale.ITALY));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateInStringAndDateFormatUsingLocaleCanada_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() throws ParseException {
|
||||
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
|
||||
|
||||
assertEquals(13, calendar.getWeekNumberFrom("20200322", "yyyyMMdd", Locale.CANADA));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateInYearMonthDayNumbersLocaleItaly_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() {
|
||||
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
|
||||
|
||||
assertEquals(12, calendar.getWeekNumberFrom(2020, 2, 22, Locale.ITALY));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateInYearMonthDayNumbersLocaleItalyChangingWeekCalculationSettings_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() {
|
||||
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
|
||||
|
||||
assertEquals(13, calendar.getWeekNumberFrom(2020, 2, 22, Calendar.SUNDAY, 4, Locale.ITALY));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateInYearMonthDayNumbersLocaleCanada_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() {
|
||||
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
|
||||
|
||||
assertEquals(13, calendar.getWeekNumberFrom(2020, 2, 22, Locale.CANADA));
|
||||
}
|
||||
}
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
package com.baeldung.weeknumber;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class WeekNumberUsingLocalDateUnitTest {
|
||||
@Test
|
||||
public void givenDateInStringAndDateFormatUsingWeekFieldsWithLocaleItaly_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
|
||||
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
|
||||
|
||||
assertEquals(12, localDate.getWeekNumberUsingWeekFiedsFrom("20200322", "yyyyMMdd", Locale.ITALY)
|
||||
.longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateInStringAndDateFormatUsingWeekFieldsWithLocaleCanada_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
|
||||
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
|
||||
|
||||
assertEquals(13, localDate.getWeekNumberUsingWeekFiedsFrom("20200322", "yyyyMMdd", Locale.CANADA)
|
||||
.longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateInStringAndDateFormatUsingChronoFieds_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
|
||||
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
|
||||
|
||||
assertEquals(12, localDate.getWeekNumberUsingChronoFieldFrom(2020, 3, 22)
|
||||
.longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateInYearMonthDayNumbersUsingWeekFieldsWithLocaleItaly_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
|
||||
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
|
||||
|
||||
assertEquals(12, localDate.getWeekNumberUsinWeekFieldsFrom(2020, 3, 22, Locale.ITALY)
|
||||
.longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateInYearMonthDayNumbersUsingWeekFieldsWithLocaleCanada_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
|
||||
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
|
||||
|
||||
assertEquals(13, localDate.getWeekNumberUsinWeekFieldsFrom(2020, 3, 22, Locale.CANADA)
|
||||
.longValue());
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.exceptionininitializererror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
public class ExceptionInInitializerErrorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStaticVar_whenThrows_thenWrapsItInAnExceptionInInitializerError() {
|
||||
assertThatThrownBy(StaticVar::new)
|
||||
.isInstanceOf(ExceptionInInitializerError.class)
|
||||
.hasCauseInstanceOf(RuntimeException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStaticBlock_whenThrows_thenWrapsItInAnExceptionInInitializerError() {
|
||||
assertThatThrownBy(StaticBlock::new)
|
||||
.isInstanceOf(ExceptionInInitializerError.class)
|
||||
.hasCauseInstanceOf(ArithmeticException.class);
|
||||
}
|
||||
|
||||
private static class CheckedConvention {
|
||||
|
||||
private static Constructor<?> constructor;
|
||||
|
||||
static {
|
||||
try {
|
||||
constructor = CheckedConvention.class.getDeclaredConstructor();
|
||||
} catch (NoSuchMethodException e) {
|
||||
throw new ExceptionInInitializerError(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class StaticVar {
|
||||
|
||||
private static int state = initializeState();
|
||||
|
||||
private static int initializeState() {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
}
|
||||
|
||||
private static class StaticBlock {
|
||||
|
||||
private static int state;
|
||||
|
||||
static {
|
||||
state = 42 / 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package com.baeldung.exceptions;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
|
||||
|
||||
public class TooManyOpenFilesExceptionLiveTest {
|
||||
|
||||
//This is not a regular UnitTest due to the fact that it depends on System.gc() to work properly.
|
||||
//As we have to force the JVM to run out of file descriptors, any other tests that uses IO may fail.
|
||||
//This may indirectly affect other tests that are part of the Jenkins Build.
|
||||
|
||||
private File tempFile;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() throws IOException {
|
||||
tempFile = File.createTempFile("testForException", "tmp");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void tearDown() {
|
||||
//Enforce a GC to clear unreferenced files and release descriptors
|
||||
System.gc();
|
||||
tempFile.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotClosingResoures_thenIOExceptionShouldBeThrown() {
|
||||
try {
|
||||
for (int x = 0; x < 1000000; x++) {
|
||||
FileInputStream leakyHandle = new FileInputStream(tempFile);
|
||||
}
|
||||
Assertions.fail("Method Should Have Failed");
|
||||
} catch (IOException e) {
|
||||
assertTrue(e.getMessage().toLowerCase().contains("too many open files"));
|
||||
} catch (Exception e) {
|
||||
Assertions.fail("Unexpected exception");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenClosingResoures_thenIOExceptionShouldNotBeThrown() {
|
||||
try {
|
||||
for (int x = 0; x < 1000000; x++) {
|
||||
FileInputStream nonLeakyHandle = null;
|
||||
try {
|
||||
nonLeakyHandle = new FileInputStream(tempFile);
|
||||
} finally {
|
||||
if (nonLeakyHandle != null) {
|
||||
nonLeakyHandle.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
assertFalse(e.getMessage().toLowerCase().contains("too many open files"));
|
||||
Assertions.fail("Method Should Not Have Failed");
|
||||
} catch (Exception e) {
|
||||
Assertions.fail("Unexpected exception");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingTryWithResoures_thenIOExceptionShouldNotBeThrown() {
|
||||
try {
|
||||
for (int x = 0; x < 1000000; x++) {
|
||||
try (FileInputStream nonLeakyHandle = new FileInputStream(tempFile)) {
|
||||
//Do something with the file
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
assertFalse(e.getMessage().toLowerCase().contains("too many open files"));
|
||||
Assertions.fail("Method Should Not Have Failed");
|
||||
} catch (Exception e) {
|
||||
Assertions.fail("Unexpected exception");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,7 @@
|
||||
<dependency>
|
||||
<groupId>com.github.tomakehurst</groupId>
|
||||
<artifactId>wiremock</artifactId>
|
||||
<version>2.26.3</version>
|
||||
<version>${wiremock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
@@ -80,6 +80,7 @@
|
||||
<properties>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<wiremock.version>2.26.3</wiremock.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user