Merge branch 'eugenp:master' into master

This commit is contained in:
Mladen Savic
2021-07-27 13:43:07 +02:00
committed by GitHub
220 changed files with 6786 additions and 237 deletions
-32
View File
@@ -84,38 +84,6 @@
</executions>
</plugin>
<plugin>
<groupId>com.bazaarvoice.maven.plugins</groupId>
<artifactId>process-exec-maven-plugin</artifactId>
<version>${process-exec-maven-plugin.version}</version>
<executions>
<!--Start Blade -->
<execution>
<id>blade-process</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
<configuration>
<name>Blade</name>
<waitForInterrupt>false</waitForInterrupt>
<arguments>
<argument>java</argument>
<argument>-jar</argument>
<argument>blade.jar</argument>
</arguments>
</configuration>
</execution>
<!--Stop all processes in reverse order -->
<execution>
<id>stop-all</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop-all</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>${assembly.plugin.version}</version>
@@ -17,8 +17,8 @@ import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
public class HttpRequestUnitTest {
@@ -51,10 +51,10 @@ public class HttpRequestUnitTest {
/*
* This test will fail as soon as the given URL returns a HTTP 2 response.
* Therefore, let's leave it commented out.
* Therefore, let's leave it ignored.
* */
@Test
@Disabled
@Test
@Ignore
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
+3
View File
@@ -0,0 +1,3 @@
### Relevant articles:
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
+48
View File
@@ -0,0 +1,48 @@
<?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-16</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-16</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>16</maven.compiler.source.version>
<maven.compiler.target.version>16</maven.compiler.target.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>
@@ -0,0 +1,23 @@
package com.baeldung.streams;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class StreamToImmutableUnitTest {
@Test
public void whenUsingStreamToList_thenReturnImmutableList() {
List<String> immutableList = Stream.of("a", "b", "c", "d")
.toList();
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
immutableList.add("e");
});
}
}
@@ -10,3 +10,5 @@
- [Overview of Java Built-in Annotations](https://www.baeldung.com/java-default-annotations)
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)
- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency)
- [Why Missing Annotations Don’t Cause ClassNotFoundException](https://www.baeldung.com/classnotfoundexception-missing-annotation)
- [Valid @SuppressWarnings Warning Names](https://www.baeldung.com/java-suppresswarnings-valid-names)
@@ -0,0 +1,46 @@
package com.baeldung.annotations;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings({"serial", "unchecked"})
public class ClassWithSuppressWarningsNames implements Serializable {
// private static final long serialVersionUID = -1166032307853492833L;
@SuppressWarnings("unused")
public static void suppressBoxingWarning() {
int value = 5;
int unusedVar = 10; // no warning here
List<Integer> list = new ArrayList<>();
list.add(Integer.valueOf(value));
}
@SuppressWarnings("deprecated")
void suppressDeprecatedWarning() {
ClassWithSuppressWarningsNames cls = new ClassWithSuppressWarningsNames();
cls.deprecatedMethod(); // no warning here
}
@SuppressWarnings("fallthrough")
String suppressFallthroughWarning() {
int day = 5;
switch (day) {
case 5:
return "This is day 5";
// break; // no warning here
case 10:
return "This is day 10";
// break;
default:
return "This default day";
}
}
@Deprecated
String deprecatedMethod() {
return "deprecated method";
}
}
@@ -0,0 +1,8 @@
package com.baeldung.missingannotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
}
@@ -0,0 +1,10 @@
package com.baeldung.missingannotation;
@A
@C(D.class)
public class B {
public static void main(String[] args) {
System.out.println("It worked");
}
}
@@ -0,0 +1,9 @@
package com.baeldung.missingannotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface C {
Class<?> value();
}
@@ -0,0 +1,4 @@
package com.baeldung.missingannotation;
public class D {
}
@@ -6,3 +6,4 @@
- [ArrayList vs. LinkedList vs. HashMap in Java](https://www.baeldung.com/java-arraylist-vs-linkedlist-vs-hashmap)
- [Java Deque vs. Stack](https://www.baeldung.com/java-deque-vs-stack)
- [Collection.toArray(new T[0]) or .toArray(new T[size])](https://www.baeldung.com/java-collection-toarray-methods)
@@ -2,3 +2,4 @@
- [Binary Semaphore vs Reentrant Lock](https://www.baeldung.com/java-binary-semaphore-vs-reentrant-lock)
- [Bad Practices With Synchronization](https://www.baeldung.com/java-synchronization-bad-practices)
- [Start Two Threads at the Exact Same Time in Java](https://www.baeldung.com/java-start-two-threads-at-same-time)
@@ -0,0 +1,86 @@
package com.baeldung.threadsstartatsametime;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Phaser;
public class ThreadsStartAtSameTime {
public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
usingCountDownLatch();
Thread.sleep(30);
usingCyclicBarrier();
Thread.sleep(30);
usingPhaser();
}
private static void usingCountDownLatch() throws InterruptedException {
System.out.println("===============================================");
System.out.println(" >>> Using CountDownLatch <<<<");
System.out.println("===============================================");
CountDownLatch latch = new CountDownLatch(1);
WorkerWithCountDownLatch worker1 = new WorkerWithCountDownLatch("Worker with latch 1", latch);
WorkerWithCountDownLatch worker2 = new WorkerWithCountDownLatch("Worker with latch 2", latch);
worker1.start();
worker2.start();
Thread.sleep(10);//simulation of some actual work
System.out.println("-----------------------------------------------");
System.out.println(" Now release the latch:");
System.out.println("-----------------------------------------------");
latch.countDown();
}
private static void usingCyclicBarrier() throws BrokenBarrierException, InterruptedException {
System.out.println("\n===============================================");
System.out.println(" >>> Using CyclicBarrier <<<<");
System.out.println("===============================================");
CyclicBarrier barrier = new CyclicBarrier(3);
WorkerWithCyclicBarrier worker1 = new WorkerWithCyclicBarrier("Worker with barrier 1", barrier);
WorkerWithCyclicBarrier worker2 = new WorkerWithCyclicBarrier("Worker with barrier 2", barrier);
worker1.start();
worker2.start();
Thread.sleep(10);//simulation of some actual work
System.out.println("-----------------------------------------------");
System.out.println(" Now open the barrier:");
System.out.println("-----------------------------------------------");
barrier.await();
}
private static void usingPhaser() throws InterruptedException {
System.out.println("\n===============================================");
System.out.println(" >>> Using Phaser <<<");
System.out.println("===============================================");
Phaser phaser = new Phaser();
phaser.register();
WorkerWithPhaser worker1 = new WorkerWithPhaser("Worker with phaser 1", phaser);
WorkerWithPhaser worker2 = new WorkerWithPhaser("Worker with phaser 2", phaser);
worker1.start();
worker2.start();
Thread.sleep(10);//simulation of some actual work
System.out.println("-----------------------------------------------");
System.out.println(" Now open the phaser barrier:");
System.out.println("-----------------------------------------------");
phaser.arriveAndAwaitAdvance();
}
}
@@ -0,0 +1,24 @@
package com.baeldung.threadsstartatsametime;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;
public class WorkerWithCountDownLatch extends Thread {
private CountDownLatch latch;
public WorkerWithCountDownLatch(String name, CountDownLatch latch) {
this.latch = latch;
setName(name);
}
@Override public void run() {
try {
System.out.printf("[ %s ] created, blocked by the latch\n", getName());
latch.await();
System.out.printf("[ %s ] starts at: %s\n", getName(), Instant.now());
// do actual work here...
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,25 @@
package com.baeldung.threadsstartatsametime;
import java.time.Instant;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class WorkerWithCyclicBarrier extends Thread {
private CyclicBarrier barrier;
public WorkerWithCyclicBarrier(String name, CyclicBarrier barrier) {
this.barrier = barrier;
this.setName(name);
}
@Override public void run() {
try {
System.out.printf("[ %s ] created, blocked by the barrier\n", getName());
barrier.await();
System.out.printf("[ %s ] starts at: %s\n", getName(), Instant.now());
// do actual work here...
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,26 @@
package com.baeldung.threadsstartatsametime;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Phaser;
public class WorkerWithPhaser extends Thread {
private Phaser phaser;
public WorkerWithPhaser(String name, Phaser phaser) {
this.phaser = phaser;
phaser.register();
setName(name);
}
@Override public void run() {
try {
System.out.printf("[ %s ] created, blocked by the phaser\n", getName());
phaser.arriveAndAwaitAdvance();
System.out.printf("[ %s ] starts at: %s\n", getName(), Instant.now());
// do actual work here...
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
@@ -13,4 +13,5 @@ This module contains articles about basic Java concurrency
- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe)
- [How to Stop Execution After a Certain Time in Java](https://www.baeldung.com/java-stop-execution-after-certain-time)
- [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception)
- [How to Get the Number of Threads in a Java Process](https://www.baeldung.com/java-get-number-of-threads)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic)
@@ -36,6 +36,16 @@
<build>
<finalName>core-java-io-conversions-2</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${source.version}</source>
<target>${target.version}</target>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
@@ -45,6 +55,8 @@
</build>
<properties>
<source.version>11</source.version>
<target.version>11</target.version>
<json.version>20200518</json.version>
<opencsv.version>4.1</opencsv.version>
</properties>
@@ -21,11 +21,11 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
import java.util.UUID;
@@ -70,6 +70,16 @@ public class JavaInputStreamToXUnitTest {
assertThat(text, equalTo(originalString));
}
@Test
public void givenUsingJava9_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
final String text = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
assertThat(text, equalTo(originalString));
}
@Test
public final void givenUsingJava7_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
@@ -155,15 +165,13 @@ public class JavaInputStreamToXUnitTest {
@Test
public final void whenConvertingToFile_thenCorrect() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
final byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
final Path path = Paths.get("src/test/resources/sample.txt");
final byte[] buffer = java.nio.file.Files.readAllBytes(path);
final File targetFile = new File("src/test/resources/targetFile.tmp");
final OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
IOUtils.closeQuietly(initialStream);
IOUtils.closeQuietly(outStream);
}
@@ -7,3 +7,4 @@ This module contains articles about core features in the Java language
- [What are Compile-time Constants in Java?](https://www.baeldung.com/java-compile-time-constants)
- [Java Objects.hash() vs Objects.hashCode()](https://www.baeldung.com/java-objects-hash-vs-objects-hashcode)
- [Referencing a Method in Javadoc Comments](https://www.baeldung.com/java-method-in-javadoc)
- [Tiered Compilation in JVM](https://www.baeldung.com/jvm-tiered-compilation)
@@ -21,6 +21,16 @@
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
@@ -0,0 +1,21 @@
package com.baeldung.tieredcompilation;
public class Article {
private String name;
private String author;
public Article(String name, String author) {
this.name = name;
this.author = author;
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
}
@@ -0,0 +1,7 @@
package com.baeldung.tieredcompilation;
public interface Formatter {
<T> String format(T object) throws Exception;
}
@@ -0,0 +1,15 @@
package com.baeldung.tieredcompilation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
public class JsonFormatter implements Formatter {
private static final JsonMapper mapper = new JsonMapper();
@Override
public <T> String format(T object) throws JsonProcessingException {
return mapper.writeValueAsString(object);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.tieredcompilation;
public class TieredCompilation {
public static void main(String[] args) throws Exception {
for (int i = 0; i < 1_000_000; i++) {
Formatter formatter;
if (i < 500_000) {
formatter = new JsonFormatter();
} else {
formatter = new XmlFormatter();
}
formatter.format(new Article("Tiered Compilation in JVM", "Baeldung"));
}
}
}
@@ -0,0 +1,15 @@
package com.baeldung.tieredcompilation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class XmlFormatter implements Formatter {
private static final XmlMapper mapper = new XmlMapper();
@Override
public <T> String format(T object) throws JsonProcessingException {
return mapper.writeValueAsString(object);
}
}
@@ -5,4 +5,5 @@ This module contains article about constructors in Java
### Relevant Articles:
- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors)
- [Java Copy Constructor](https://www.baeldung.com/java-copy-constructor)
- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error)
- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error)
- [Private Constructors in Java](https://www.baeldung.com/java-private-constructors)
@@ -9,4 +9,5 @@ This module contains articles about modifiers in Java
- [The “final” Keyword in Java](https://www.baeldung.com/java-final)
- [A Guide to the Static Keyword in Java](https://www.baeldung.com/java-static)
- [Static and Default Methods in Interfaces in Java](https://www.baeldung.com/java-static-default-methods)
- [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp)
- [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp)
- [Static Classes Versus the Singleton Pattern in Java](https://www.baeldung.com/java-static-class-vs-singleton)
@@ -0,0 +1,30 @@
package com.baeldung.staticsingletondifference;
public class CachingSingleton implements SingletonInterface {
private CachingSingleton() {
}
private static class SingletonHolder {
public static final CachingSingleton instance = new CachingSingleton();
}
public static CachingSingleton getInstance() {
return SingletonHolder.instance;
}
@Override
public String describeMe() {
return "Caching Responsibilities";
}
@Override
public String passOnLocks(MyLock lock) {
return lock.takeLock(1);
}
@Override
public void increment() {
throw new UnsupportedOperationException("Not Supported Here");
}
}

Some files were not shown because too many files have changed in this diff Show More