This commit is contained in:
Philippe Soares
2020-02-08 23:47:22 -05:00
1885 changed files with 15052 additions and 4913 deletions
+1
View File
@@ -12,3 +12,4 @@ This module contains articles about Java 11 core features
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
- [Guide to jlink](https://www.baeldung.com/jlink)
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
- [Benchmark JDK Collections vs Eclipse Collections](https://www.baeldung.com/jdk-collections-vs-eclipse-collections)
+3 -2
View File
@@ -42,12 +42,12 @@
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>10.0.0</version>
<version>${eclipse.collections.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections-api</artifactId>
<version>10.0.0</version>
<version>${eclipse.collections.version}</version>
</dependency>
</dependencies>
@@ -108,6 +108,7 @@
<assertj.version>3.11.1</assertj.version>
<uberjar.name>benchmarks</uberjar.name>
<jmh.version>1.22</jmh.version>
<eclipse.collections.version>10.0.0</eclipse.collections.version>
</properties>
</project>
@@ -0,0 +1,29 @@
package com.baeldung.patternreuse;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PatternJava11UnitTest {
@Test
public void givenPreCompiledPattern_whenCallAsMatchPredicate_thenReturnMatchPredicateToMatchesPattern() {
List<String> namesToValidate = Arrays.asList("Fabio Silva", "Fabio Luis Silva");
Pattern firstLastNamePreCompiledPattern = Pattern.compile("[a-zA-Z]{3,} [a-zA-Z]{3,}");
Predicate<String> patternAsMatchPredicate = firstLastNamePreCompiledPattern.asMatchPredicate();
List<String> validatedNames = namesToValidate.stream()
.filter(patternAsMatchPredicate)
.collect(Collectors.toList());
assertTrue(validatedNames.contains("Fabio Silva"));
assertFalse(validatedNames.contains("Fabio Luis Silva"));
}
}
+2 -1
View File
@@ -41,7 +41,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
@@ -53,6 +53,7 @@
<maven.compiler.source.version>13</maven.compiler.source.version>
<maven.compiler.target.version>13</maven.compiler.target.version>
<assertj.version>3.6.1</assertj.version>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
</properties>
</project>
@@ -0,0 +1,27 @@
package com.baeldung.newfeatures;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class SwitchExpressionsWithYieldUnitTest {
@Test
@SuppressWarnings("preview")
public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() {
var me = 4;
var operation = "squareMe";
var result = switch (operation) {
case "doubleMe" -> {
yield me * 2;
}
case "squareMe" -> {
yield me * me;
}
default -> me;
};
assertEquals(16, result);
}
}
@@ -0,0 +1,39 @@
package com.baeldung.newfeatures;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class TextBlocksUnitTest {
private static final String JSON_STRING = "{\r\n" + "\"name\" : \"Baeldung\",\r\n" + "\"website\" : \"https://www.%s.com/\"\r\n" + "}";
@SuppressWarnings("preview")
private static final String TEXT_BLOCK_JSON = """
{
"name" : "Baeldung",
"website" : "https://www.%s.com/"
}
""";
@Test
public void whenTextBlocks_thenStringOperationsWork() {
assertThat(TEXT_BLOCK_JSON.contains("Baeldung")).isTrue();
assertThat(TEXT_BLOCK_JSON.indexOf("www")).isGreaterThan(0);
assertThat(TEXT_BLOCK_JSON.length()).isGreaterThan(0);
}
@SuppressWarnings("removal")
@Test
public void whenTextBlocks_thenFormattedWorksAsFormat() {
assertThat(TEXT_BLOCK_JSON.formatted("baeldung")
.contains("www.baeldung.com")).isTrue();
assertThat(String.format(JSON_STRING, "baeldung")
.contains("www.baeldung.com")).isTrue();
}
}
+53
View File
@@ -0,0 +1,53 @@
<?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>
<groupId>com.baeldung</groupId>
<artifactId>core-java-14</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>core-java-14</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>
<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>
<compilerArgs>
<compilerArg>
--enable-preview
</compilerArg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>14</maven.compiler.source.version>
<maven.compiler.target.version>14</maven.compiler.target.version>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
</properties>
</project>
@@ -0,0 +1,50 @@
package com.baeldung.serial;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.ObjectStreamField;
import java.io.Serial;
import java.io.Serializable;
/**
* Class showcasing the usage of the Java 14 @Serial annotation.
*
* @author Donato Rimenti
*/
public class MySerialClass implements Serializable {
@Serial
private static final ObjectStreamField[] serialPersistentFields = null;
@Serial
private static final long serialVersionUID = 1;
@Serial
private void writeObject(ObjectOutputStream stream) throws IOException {
// ...
}
@Serial
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
// ...
}
@Serial
private void readObjectNoData() throws ObjectStreamException {
// ...
}
@Serial
private Object writeReplace() throws ObjectStreamException {
// ...
return null;
}
@Serial
private Object readResolve() throws ObjectStreamException {
// ...
return null;
}
}
+1 -1
View File
@@ -61,7 +61,7 @@
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
@@ -19,6 +19,16 @@
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
@@ -37,13 +47,39 @@
<filtering>true</filtering>
</resource>
</resources>
<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>
<jmh.version>1.19</jmh.version>
<!-- util -->
<commons-lang3.version>3.9</commons-lang3.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
<shade.plugin.version>3.2.0</shade.plugin.version>
</properties>
</project>
@@ -0,0 +1,72 @@
package com.baeldung.arraysort;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5)
@Measurement(iterations = 10)
@Fork(2)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class ArraySortingBenchmark {
@State(Scope.Benchmark)
public static class ArrayContainer {
@Param({ "1000", "10000", "100000", "1000000" })
int arraySize;
// initial unsorted array
int[] unsortedArray;
//cloned array to sort
int[] arrayToSort;
@Setup(Level.Trial)
public void createUnSortedArray() {
unsortedArray = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
unsortedArray[i] = new Random().nextInt(1000);
}
}
@Setup(Level.Invocation)
public void createUnSortedArrayCopy() {
arrayToSort = unsortedArray.clone();
}
int[] getArrayToSort() {
return arrayToSort;
}
}
@Benchmark
public void benchmark_arrays_parallel_sort(ArrayContainer d, Blackhole b) {
int[] arr = d.getArrayToSort();
Arrays.parallelSort(arr);
b.consume(arr);
}
@Benchmark
public void benchmark_arrays_sort(ArrayContainer d, Blackhole b) {
int[] arr = d.getArrayToSort();
Arrays.sort(arr);
b.consume(arr);
}
}
@@ -0,0 +1,185 @@
package com.baeldung.arraysort;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import java.util.Arrays;
import java.util.Random;
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
* Time taken by JUnit test cases can be seen in JUnit Runner
* @author rchaudhary23
*
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SortComparisonUnitTest {
private int[] sizeOfArrays = { 1000, 10000, 100000, 1000000 };
private int[] _1000_elements_array;
private int[] _10000_elements_array;
private int[] _100000_elements_array;
private int[] _1000000_elements_array;
@Before
public void setUp() throws Exception {
_1000_elements_array = new int[sizeOfArrays[0]];
_10000_elements_array = new int[sizeOfArrays[1]];
_100000_elements_array = new int[sizeOfArrays[2]];
_1000000_elements_array = new int[sizeOfArrays[3]];
Random random = new Random();
for (int i = 0; i < sizeOfArrays[0]; i++) {
_1000_elements_array[i] = random.nextInt(sizeOfArrays[0]) + random.nextInt(sizeOfArrays[0]);
}
for (int i = 0; i < sizeOfArrays[1]; i++) {
_10000_elements_array[i] = random.nextInt(sizeOfArrays[1]) + random.nextInt(sizeOfArrays[1]);
}
for (int i = 0; i < sizeOfArrays[2]; i++) {
_100000_elements_array[i] = random.nextInt(sizeOfArrays[2]) + random.nextInt(sizeOfArrays[2]);
}
for (int i = 0; i < sizeOfArrays[3]; i++) {
_1000000_elements_array[i] = random.nextInt(sizeOfArrays[3]) + random.nextInt(sizeOfArrays[3]);
}
}
@Test
public void givenArrayOfIntegers_whenUsingArraysSortMethod_thenSortFullArrayInAscendingOrder() {
int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 };
int[] expected = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Arrays.sort(array);
assertArrayEquals(expected, array);
}
@Test
public void givenArrayOfIntegers_whenUsingArraysSortMethodWithRange_thenSortRangeOfArrayInAscendingOrder() {
int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 };
int[] expected = { 10, 4, 1, 2, 6, 7, 8, 9, 3, 5 };
Arrays.sort(array, 2, 8);
assertArrayEquals(expected, array);
}
@Test
public void givenArrayOfIntegers_whenUsingArraysParallelSortMethod_thenSortFullArrayInAscendingOrder() {
int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 };
int[] expected = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Arrays.parallelSort(array);
assertArrayEquals(expected, array);
}
@Test
public void givenArrayOfIntegers_whenUsingArraysParallelSortMethodWithRange_thenSortRangeOfArrayInAscendingOrder() {
int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 };
int[] expected = { 10, 4, 1, 2, 6, 7, 8, 9, 3, 5 };
Arrays.parallelSort(array, 2, 8);
assertArrayEquals(expected, array);
}
@Test
public void givenIntegerArrayOf1000Elements_whenUsingArraysSortMethod_thenSortFullArrayInAscendingOrder() {
int[] sequentialDataSet = Arrays.copyOf(_1000_elements_array, _1000_elements_array.length);
Arrays.sort(sequentialDataSet);
assertNotNull(sequentialDataSet);
assertNotSame(Arrays.copyOf(_1000_elements_array, _1000_elements_array.length), sequentialDataSet);
}
@Test
public void givenIntegerArrayOf1000Elements_whenUsingArraysParallelSortMethod_thenSortFullArrayInAscendingOrder() {
int[] parallelDataSet = Arrays.copyOf(_1000_elements_array, _1000_elements_array.length);
Arrays.parallelSort(parallelDataSet);
assertNotNull(parallelDataSet);
assertNotSame(Arrays.copyOf(_1000_elements_array, _1000_elements_array.length), parallelDataSet);
}
@Test
public void givenIntegerArrayOf10000Elements_whenUsingArraysSortMethod_thenSortFullArrayInAscendingOrder() {
int[] sequentialDataSet = Arrays.copyOf(_10000_elements_array, _10000_elements_array.length);
Arrays.sort(sequentialDataSet);
assertNotNull(sequentialDataSet);
assertNotSame(Arrays.copyOf(_10000_elements_array, _10000_elements_array.length), sequentialDataSet);
}
@Test
public void givenIntegerArrayOf10000Elements_whenUsingArraysParallelSortMethod_thenSortFullArrayInAscendingOrder() {
int[] parallelDataSet = Arrays.copyOf(_10000_elements_array, _10000_elements_array.length);
Arrays.parallelSort(parallelDataSet);
assertNotNull(parallelDataSet);
assertNotSame(Arrays.copyOf(_10000_elements_array, _10000_elements_array.length), parallelDataSet);
}
@Test
public void givenIntegerArrayOf100000Elements_whenUsingArraysSortMethod_thenSortFullArrayInAscendingOrder() {
int[] sequentialDataSet = Arrays.copyOf(_100000_elements_array, _100000_elements_array.length);
Arrays.sort(sequentialDataSet);
assertNotNull(sequentialDataSet);
assertNotSame(Arrays.copyOf(_100000_elements_array, _100000_elements_array.length), sequentialDataSet);
}
@Test
public void givenIntegerArrayOf100000Elements_whenUsingArraysParallelSortMethod_thenSortFullArrayInAscendingOrder() {
int[] parallelDataSet = Arrays.copyOf(_100000_elements_array, _100000_elements_array.length);
Arrays.parallelSort(parallelDataSet);
assertNotNull(parallelDataSet);
assertNotSame(Arrays.copyOf(_100000_elements_array, _100000_elements_array.length), parallelDataSet);
}
@Test
public void givenIntegerArrayOf1000000Elements_whenUsingArraysSortMethod_thenSortFullArrayInAscendingOrder() {
int[] sequentialDataSet = Arrays.copyOf(_1000000_elements_array, _1000000_elements_array.length);
Arrays.sort(sequentialDataSet);
assertNotNull(sequentialDataSet);
assertNotSame(Arrays.copyOf(_1000000_elements_array, _1000000_elements_array.length), sequentialDataSet);
}
@Test
public void givenIntegerArrayOf1000000Elements_whenUsingArraysParallelSortMethod_thenSortFullArrayInAscendingOrder() {
int[] parallelDataSet = Arrays.copyOf(_1000000_elements_array, _1000000_elements_array.length);
Arrays.parallelSort(parallelDataSet);
assertNotNull(parallelDataSet);
assertNotSame(Arrays.copyOf(_1000000_elements_array, _1000000_elements_array.length), parallelDataSet);
}
@After
public void tearDown() throws Exception {
sizeOfArrays = null;
_1000_elements_array = null;
_10000_elements_array = null;
_100000_elements_array = null;
_1000000_elements_array = null;
}
}
+9 -7
View File
@@ -75,7 +75,7 @@
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
@@ -94,7 +94,7 @@
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
@@ -118,7 +118,7 @@
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
@@ -133,7 +133,7 @@
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
@@ -155,7 +155,7 @@
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
@@ -183,8 +183,8 @@
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<source>${source.version}</source>
<target>${target.version}</target>
</configuration>
</plugin>
</plugins>
@@ -373,6 +373,8 @@
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
</properties>
</project>
@@ -1,4 +1,4 @@
package org.baeldung.java.collections;
package com.baeldung.collections;
import com.google.common.collect.Sets;
import org.junit.Before;
@@ -1,4 +1,4 @@
package org.baeldung.java.collections;
package com.baeldung.collections;
import com.google.common.collect.ImmutableList;
import org.apache.commons.collections4.ListUtils;
@@ -3,13 +3,13 @@
This module contains articles about the Java List collection
### Relevant Articles:
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Check If Two Lists are Equal in Java](https://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
- [A Guide to the Java LinkedList](https://www.baeldung.com/java-linkedlist)
- [Java List UnsupportedOperationException](https://www.baeldung.com/java-list-unsupported-operation-exception)
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
- [Flattening Nested Collections in Java](https://www.baeldung.com/java-flatten-nested-collections)
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
- [Searching for a String in an ArrayList](https://www.baeldung.com/java-search-string-arraylist)
- [[<-- Prev]](/core-java-modules/core-java-collections-list)[[Next -->]](/core-java-modules/core-java-collections-list-3)
@@ -1,4 +1,4 @@
package org.baeldung.java.lists;
package com.baeldung.java.list;
import org.junit.Assert;
import org.junit.Test;
@@ -1,2 +0,0 @@
### Relevant Articles:
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
@@ -24,11 +24,21 @@ public class DuplicatesCounter {
return resultMap;
}
public static <T> Map<T, Long> countByClassicalLoopWithMapCompute(List<T> inputList) {
public static <T> Map<T, Long> countByForEachLoopWithGetOrDefault(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
for (T element : inputList) {
resultMap.compute(element, (k, v) -> v == null ? 1 : v + 1);
}
inputList.forEach(e -> resultMap.put(e, resultMap.getOrDefault(e, 0L) + 1L));
return resultMap;
}
public static <T> Map<T, Long> countByForEachLoopWithMapCompute(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
inputList.forEach(e -> resultMap.compute(e, (k, v) -> v == null ? 1L : v + 1L));
return resultMap;
}
public static <T> Map<T, Long> countByForEachLoopWithMapMerge(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
inputList.forEach(e -> resultMap.merge(e, 1L, Long::sum));
return resultMap;
}
@@ -11,7 +11,6 @@ import static org.assertj.core.data.MapEntry.entry;
class DuplicatesCounterUnitTest {
private static List<String> INPUT_LIST = Lists.list(
"expect1",
"expect2", "expect2",
@@ -24,10 +23,21 @@ class DuplicatesCounterUnitTest {
verifyResult(result);
}
@Test
void givenInput_whenCountByForEachLoopWithGetOrDefault_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithGetOrDefault(INPUT_LIST);
verifyResult(result);
}
@Test
void givenInput_whenCountByClassicalLoopWithMapCompute_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByClassicalLoopWithMapCompute(INPUT_LIST);
void givenInput_whenCountByForEachLoopWithMapCompute_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithMapCompute(INPUT_LIST);
verifyResult(result);
}
@Test
void givenInput_whenCountByForEachLoopWithMapMerge_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithMapMerge(INPUT_LIST);
verifyResult(result);
}
@@ -1,4 +1,4 @@
package org.baeldung.java.collections;
package com.baeldung.collections;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
@@ -1,4 +1,4 @@
package org.baeldung;
package com.baeldung.list.random;
import com.google.common.collect.Lists;
import org.junit.Test;
@@ -23,6 +23,37 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-aspects</artifactId>
<version>${jcabi-aspects.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectjrt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.cactoos</groupId>
<artifactId>cactoos</artifactId>
<version>${cactoos.version}</version>
</dependency>
<dependency>
<groupId>com.ea.async</groupId>
<artifactId>ea-async</artifactId>
<version>${ea-async.version}</version>
</dependency>
</dependencies>
<build>
@@ -36,6 +67,30 @@
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-maven-plugin</artifactId>
<version>${jcabi-maven-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>ajc</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectjtools.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
<resources>
<resource>
@@ -49,6 +104,14 @@
<assertj.version>3.14.0</assertj.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<jcabi-aspects.version>0.22.6</jcabi-aspects.version>
<aspectjrt.version>1.9.5</aspectjrt.version>
<guava.version>28.2-jre</guava.version>
<cactoos.version>0.43</cactoos.version>
<ea-async.version>1.2.3</ea-async.version>
<jcabi-maven-plugin.version>0.14.1</jcabi-maven-plugin.version>
<aspectjtools.version>1.9.1</aspectjtools.version>
<aspectjweaver.version>1.9.1</aspectjweaver.version>
</properties>
</project>
@@ -0,0 +1,57 @@
package com.baeldung.async;
import static com.ea.async.Async.await;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import com.ea.async.Async;
public class EAAsyncExample {
static {
Async.init();
}
public static void main(String[] args) throws Exception {
usingCompletableFuture();
usingAsyncAwait();
}
public static void usingCompletableFuture() throws InterruptedException, ExecutionException, Exception {
CompletableFuture<Void> completableFuture = hello()
.thenComposeAsync(hello -> mergeWorld(hello))
.thenAcceptAsync(helloWorld -> print(helloWorld))
.exceptionally( throwable -> {
System.out.println(throwable.getCause());
return null;
});
completableFuture.get();
}
public static CompletableFuture<String> hello() {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
return completableFuture;
}
public static CompletableFuture<String> mergeWorld(String s) {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
return s + " World!";
});
return completableFuture;
}
public static void print(String str) {
CompletableFuture.runAsync(() -> System.out.println(str));
}
private static void usingAsyncAwait() {
try {
String hello = await(hello());
String helloWorld = await(mergeWorld(hello));
await(CompletableFuture.runAsync(() -> print(helloWorld)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,183 @@
package com.baeldung.async;
import static com.ea.async.Async.await;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.google.common.util.concurrent.AsyncCallable;
import com.google.common.util.concurrent.Callables;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.jcabi.aspects.Async;
import com.jcabi.aspects.Loggable;
public class JavaAsync {
static {
com.ea.async.Async.init();
}
private static final ExecutorService threadpool = Executors.newCachedThreadPool();
public static void main (String[] args) throws InterruptedException, ExecutionException {
int number = 20;
//Thread Example
factorialUsingThread(number).start();
//FutureTask Example
Future<Long> futureTask = factorialUsingFutureTask(number);
System.out.println("Factorial of " + number + " is: " + futureTask.get());
// CompletableFuture Example
Future<Long> completableFuture = factorialUsingCompletableFuture(number);
System.out.println("Factorial of " + number + " is: " + completableFuture.get());
// EA Async example
System.out.println("Factorial of " + number + " is: " + factorialUsingEAAsync(number));
// cactoos async example
Future<Long> asyncFuture = factorialUsingCactoos(number);
System.out.println("Factorial of " + number + " is: " + asyncFuture.get());
// Guava example
ListenableFuture<Long> guavaFuture = factorialUsingGuavaServiceSubmit(number);
System.out.println("Factorial of " + number + " is: " + guavaFuture.get());
ListenableFuture<Long> guavaFutures = factorialUsingGuavaFutures(number);
System.out.println("Factorial of " + number + " is: " + guavaFutures.get());
// @async jcabi-aspect example
Future<Long> aspectFuture = factorialUsingJcabiAspect(number);
System.out.println("Factorial of " + number + " is: " + aspectFuture.get());
}
/**
* Finds factorial of a number
* @param number
* @return
*/
public static long factorial(int number) {
long result = 1;
for(int i=number;i>0;i--) {
result *= i;
}
return result;
}
/**
* Finds factorial of a number using Thread
* @param number
* @return
*/
@Loggable
public static Thread factorialUsingThread(int number) {
Thread newThread = new Thread(() -> {
System.out.println("Factorial of " + number + " is: " + factorial(number));
});
return newThread;
}
/**
* Finds factorial of a number using FutureTask
* @param number
* @return
*/
@Loggable
public static Future<Long> factorialUsingFutureTask(int number) {
Future<Long> futureTask = threadpool.submit(() -> factorial(number));
while (!futureTask.isDone()) {
System.out.println("FutureTask is not finished yet...");
}
return futureTask;
}
/**
* Finds factorial of a number using CompletableFuture
* @param number
* @return
*/
@Loggable
public static Future<Long> factorialUsingCompletableFuture(int number) {
CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> factorial(number));
return completableFuture;
}
/**
* Finds factorial of a number using EA Async
* @param number
* @return
*/
@Loggable
public static long factorialUsingEAAsync(int number) {
CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> factorial(number));
long result = await(completableFuture);
return result;
}
/**
* Finds factorial of a number using Async of Cactoos
* @param number
* @return
* @throws InterruptedException
* @throws ExecutionException
*/
@Loggable
public static Future<Long> factorialUsingCactoos(int number) throws InterruptedException, ExecutionException {
org.cactoos.func.Async<Integer, Long> asyncFunction = new org.cactoos.func.Async<Integer, Long>(input -> factorial(input));
Future<Long> asyncFuture = asyncFunction.apply(number);
return asyncFuture;
}
/**
* Finds factorial of a number using Guava's ListeningExecutorService.submit()
* @param number
* @return
*/
@Loggable
public static ListenableFuture<Long> factorialUsingGuavaServiceSubmit(int number) {
ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool);
ListenableFuture<Long> factorialFuture = (ListenableFuture<Long>) service.submit(()-> factorial(number));
return factorialFuture;
}
/**
* Finds factorial of a number using Guava's Futures.submitAsync()
* @param number
* @return
*/
@Loggable
public static ListenableFuture<Long> factorialUsingGuavaFutures(int number) {
ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool);
AsyncCallable<Long> asyncCallable = Callables.asAsyncCallable(new Callable<Long>() {
public Long call() {
return factorial(number);
}
}, service);
return Futures.submitAsync(asyncCallable, service);
}
/**
* Finds factorial of a number using @Async of jcabi-aspects
* @param number
* @return
*/
@Async
@Loggable
public static Future<Long> factorialUsingJcabiAspect(int number) {
Future<Long> factorialFuture = CompletableFuture.supplyAsync(() -> factorial(number));
return factorialFuture;
}
}
@@ -0,0 +1,85 @@
package com.baeldung.workstealing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.atomic.AtomicInteger;
public class PrimeNumbers extends RecursiveAction {
private int lowerBound;
private int upperBound;
private int granularity;
static final List<Integer> GRANULARITIES
= Arrays.asList(1, 10, 100, 1000, 10000);
private AtomicInteger noOfPrimeNumbers;
PrimeNumbers(int lowerBound, int upperBound, int granularity, AtomicInteger noOfPrimeNumbers) {
this.lowerBound = lowerBound;
this.upperBound = upperBound;
this.granularity = granularity;
this.noOfPrimeNumbers = noOfPrimeNumbers;
}
PrimeNumbers(int upperBound) {
this(1, upperBound, 100, new AtomicInteger(0));
}
private PrimeNumbers(int lowerBound, int upperBound, AtomicInteger noOfPrimeNumbers) {
this(lowerBound, upperBound, 100, noOfPrimeNumbers);
}
private List<PrimeNumbers> subTasks() {
List<PrimeNumbers> subTasks = new ArrayList<>();
for (int i = 1; i <= this.upperBound / granularity; i++) {
int upper = i * granularity;
int lower = (upper - granularity) + 1;
subTasks.add(new PrimeNumbers(lower, upper, noOfPrimeNumbers));
}
return subTasks;
}
@Override
protected void compute() {
if (((upperBound + 1) - lowerBound) > granularity) {
ForkJoinTask.invokeAll(subTasks());
} else {
findPrimeNumbers();
}
}
void findPrimeNumbers() {
for (int num = lowerBound; num <= upperBound; num++) {
if (isPrime(num)) {
noOfPrimeNumbers.getAndIncrement();
}
}
}
private boolean isPrime(int number) {
if (number == 2) {
return true;
}
if (number == 1 || number % 2 == 0) {
return false;
}
int noOfNaturalNumbers = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
noOfNaturalNumbers++;
}
}
return noOfNaturalNumbers == 2;
}
public int noOfPrimeNumbers() {
return noOfPrimeNumbers.intValue();
}
}
@@ -1,6 +1,7 @@
package com.baeldung.rejection;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
@@ -28,24 +29,26 @@ public class SaturationPolicyUnitTest {
}
}
@Ignore
@Test
public void givenAbortPolicy_WhenSaturated_ThenShouldThrowRejectedExecutionException() {
executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new AbortPolicy());
executor.execute(() -> waitFor(100));
executor.execute(() -> waitFor(250));
assertThatThrownBy(() -> executor.execute(() -> System.out.println("Will be rejected"))).isInstanceOf(RejectedExecutionException.class);
}
@Ignore
@Test
public void givenCallerRunsPolicy_WhenSaturated_ThenTheCallerThreadRunsTheTask() {
executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new CallerRunsPolicy());
executor.execute(() -> waitFor(100));
executor.execute(() -> waitFor(250));
long startTime = System.nanoTime();
executor.execute(() -> waitFor(100));
double blockedDuration = (System.nanoTime() - startTime) / 1_000_000.0;
long startTime = System.currentTimeMillis();
executor.execute(() -> waitFor(500));
long blockedDuration = System.currentTimeMillis() - startTime;
assertThat(blockedDuration).isGreaterThanOrEqualTo(100);
assertThat(blockedDuration).isGreaterThanOrEqualTo(500);
}
@Test
@@ -0,0 +1,101 @@
package com.baeldung.workstealing;
import org.junit.Test;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import static org.junit.Assert.fail;
public class PrimeNumbersUnitTest {
private static Logger logger = Logger.getAnonymousLogger();
@Test
public void givenPrimesCalculated_whenUsingPoolsAndOneThread_thenOneThreadSlowest() {
Options opt = new OptionsBuilder()
.include(Benchmarker.class.getSimpleName())
.forks(1)
.build();
try {
new Runner(opt).run();
} catch (RunnerException e) {
fail();
}
}
@Test
public void givenNewWorkStealingPool_whenGettingPrimes_thenStealCountChanges() {
StringBuilder info = new StringBuilder();
for (int granularity : PrimeNumbers.GRANULARITIES) {
int parallelism = ForkJoinPool.getCommonPoolParallelism();
ForkJoinPool pool =
(ForkJoinPool) Executors.newWorkStealingPool(parallelism);
stealCountInfo(info, granularity, pool);
}
logger.info("\nExecutors.newWorkStealingPool ->" + info.toString());
}
@Test
public void givenCommonPool_whenGettingPrimes_thenStealCountChangesSlowly() {
StringBuilder info = new StringBuilder();
for (int granularity : PrimeNumbers.GRANULARITIES) {
ForkJoinPool pool = ForkJoinPool.commonPool();
stealCountInfo(info, granularity, pool);
}
logger.info("\nForkJoinPool.commonPool ->" + info.toString());
}
private void stealCountInfo(StringBuilder info, int granularity, ForkJoinPool forkJoinPool) {
PrimeNumbers primes = new PrimeNumbers(1, 10000, granularity, new AtomicInteger(0));
forkJoinPool.invoke(primes);
forkJoinPool.shutdown();
long steals = forkJoinPool.getStealCount();
String output = "\nGranularity: [" + granularity + "], Steals: [" + steals + "]";
info.append(output);
}
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
@Fork(value = 2, warmups = 1, jvmArgs = {"-Xms2G", "-Xmx2G"})
public static class Benchmarker {
@Benchmark
public void singleThread() {
PrimeNumbers primes = new PrimeNumbers(10000);
primes.findPrimeNumbers(); // get prime numbers using a single thread
}
@Benchmark
public void commonPoolBenchmark() {
PrimeNumbers primes = new PrimeNumbers(10000);
ForkJoinPool pool = ForkJoinPool.commonPool();
pool.invoke(primes);
pool.shutdown();
}
@Benchmark
public void newWorkStealingPoolBenchmark() {
PrimeNumbers primes = new PrimeNumbers(10000);
int parallelism = ForkJoinPool.getCommonPoolParallelism();
ForkJoinPool stealer = (ForkJoinPool) Executors.newWorkStealingPool(parallelism);
stealer.invoke(primes);
stealer.shutdown();
}
}
}

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