Merge branch 'master' into BAEL-6541-convert-relative-path

This commit is contained in:
tienvn
2023-07-08 00:12:28 +07:00
529 changed files with 8371 additions and 1971 deletions
+1
View File
@@ -2,3 +2,4 @@
- [Record Patterns in Java 19](https://www.baeldung.com/java-19-record-patterns)
- [Structured Concurrency in Java 19](https://www.baeldung.com/java-structured-concurrency)
- [Possible Root Causes for High CPU Usage in Java](https://www.baeldung.com/java-high-cpu-usage-causes)
- [The Vector API in Java 19](https://www.baeldung.com/java-vector-api)
+1
View File
@@ -21,6 +21,7 @@
<source>19</source>
<target>19</target>
<compilerArgs>--enable-preview</compilerArgs>
<compilerArgs>--add-modules=jdk.incubator.vector</compilerArgs>
</configuration>
</plugin>
</plugins>
@@ -0,0 +1,100 @@
package com.baeldung.vectors;
import jdk.incubator.vector.FloatVector;
import jdk.incubator.vector.IntVector;
import jdk.incubator.vector.VectorOperators;
import jdk.incubator.vector.VectorSpecies;
/**
* This class contains examples of the Vector API in Java, more specifically the fourth incubator to the Vector API.
* There are scalar and vector methods written here and the method names will specify the type.
* Note that, the code is written without any benchmarking done and without any assumption of it being run on
* a SIMD processor, or any specific compiler.
*/
public class VectorAPIExamples {
static final VectorSpecies<Integer> SPECIES = IntVector.SPECIES_PREFERRED;
static final VectorSpecies<Float> PREFERRED_SPECIES = FloatVector.SPECIES_PREFERRED;
public int[] addTwoScalarArrays(int[] arr1, int[] arr2) {
int[] result = new int[arr1.length];
for (int i = 0; i < arr1.length; i++) {
result[i] = arr1[i] + arr2[i];
}
return result;
}
public int[] addTwoVectorArrays(int[] arr1, int[] arr2) {
var v1 = IntVector.fromArray(SPECIES, arr1, 0);
var v2 = IntVector.fromArray(SPECIES, arr2, 0);
var result = v1.add(v2);
return result.toArray();
}
public int[] addTwoVectorsWIthHigherShape(int[] arr1, int[] arr2) {
int[] finalResult = new int[arr1.length];
for (int i = 0; i < arr1.length; i += SPECIES.length()) {
var v1 = IntVector.fromArray(SPECIES, arr1, i);
var v2 = IntVector.fromArray(SPECIES, arr2, i);
var result = v1.add(v2);
result.intoArray(finalResult, i);
}
return finalResult;
}
public int[] addTwoVectorsWithMasks(int[] arr1, int[] arr2) {
int[] finalResult = new int[arr1.length];
int i = 0;
for (; i < SPECIES.loopBound(arr1.length); i += SPECIES.length()) {
var mask = SPECIES.indexInRange(i, arr1.length);
var v1 = IntVector.fromArray(SPECIES, arr1, i, mask);
var v2 = IntVector.fromArray(SPECIES, arr2, i, mask);
var result = v1.add(v2, mask);
result.intoArray(finalResult, i, mask);
}
// tail cleanup loop
for (; i < arr1.length; i++) {
finalResult[i] = arr1[i] + arr2[i];
}
return finalResult;
}
public float[] scalarNormOfTwoArrays(float[] arr1, float[] arr2) {
float[] finalResult = new float[arr1.length];
for (int i = 0; i < arr1.length; i++) {
finalResult[i] = (arr1[i] * arr1[i] + arr2[i] * arr2[i]) * -1.0f;
}
return finalResult;
}
public float[] vectorNormalForm(float[] arr1, float[] arr2) {
float[] finalResult = new float[arr1.length];
int i = 0;
int upperBound = SPECIES.loopBound(arr1.length);
for (; i < upperBound; i += SPECIES.length()) {
var va = FloatVector.fromArray(PREFERRED_SPECIES, arr1, i);
var vb = FloatVector.fromArray(PREFERRED_SPECIES, arr2, i);
var vc = va.mul(va)
.add(vb.mul(vb))
.neg();
vc.intoArray(finalResult, i);
}
// tail cleanup
for (; i < arr1.length; i++) {
finalResult[i] = (arr1[i] * arr1[i] + arr2[i] * arr2[i]) * -1.0f;
}
return finalResult;
}
public double averageOfaVector(int[] arr) {
double sum = 0;
for (int i = 0; i < arr.length; i += SPECIES.length()) {
var mask = SPECIES.indexInRange(i, arr.length);
var V = IntVector.fromArray(SPECIES, arr, i, mask);
sum += V.reduceLanes(VectorOperators.ADD, mask);
}
return sum / arr.length;
}
}
@@ -0,0 +1,48 @@
package com.baeldung.vectors;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
public class VectorAPIUnitTest {
VectorAPIExamples vector = new VectorAPIExamples();
@Test
public void whenTwoArraysProvided_thenVerifyScalarAdd() {
int[] arr1 = { 1, 2, 3, 4 };
int[] arr2 = { 100, 200, 300, 400 };
int[] result = { 101, 202, 303, 404 };
assertArrayEquals(result, vector.addTwoScalarArrays(arr1, arr2));
}
@Test
public void whenTwoArraysProvided_thenVerifyVectorAdd() {
int[] arr1 = { 1, 2, 3, 4 };
int[] arr2 = { 100, 200, 300, 400 };
int[] result = { 101, 202, 303, 404 };
assertArrayEquals(result, vector.addTwoVectorsWithMasks(arr1, arr2));
}
@Test
public void whenTwoValuesProvided_thenComputeScalarNorm() {
float[] arr1 = { 1, 2.3f };
float[] arr2 = { 1.3f, 2.0f };
float[] result = { -2.6899998f, -9.29f };
Assertions.assertArrayEquals(result, vector.scalarNormOfTwoArrays(arr1, arr2));
}
@Test
public void whenTwoValuesProvided_thenComputeVectorNorm() {
float[] arr1 = { 1, 2.3f };
float[] arr2 = { 1.3f, 2.0f };
float[] result = { -2.6899998f, -9.29f };
Assertions.assertArrayEquals(result, vector.vectorNormalForm(arr1, arr2));
}
@Test
public void whenArrayProvided_thenComputeVectorAverage() {
int[] arr = { 100, 200, 300, 400 };
Assertions.assertEquals(250.0, vector.averageOfaVector(arr));
}
}
@@ -0,0 +1,31 @@
package com.baeldung.zipentries;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipEntryReader {
public static void readZipEntries(String filePath) throws IOException {
try (ZipFile zipFile = new ZipFile(filePath)) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
// Check if entry is a directory
if (!entry.isDirectory()) {
// Read and process the entry contents using the inputStream
try (InputStream inputStream = zipFile.getInputStream(entry);
Scanner scanner = new Scanner(inputStream);) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
}
}
}
}
}
}
@@ -0,0 +1,17 @@
package com.baeldung.zipentries;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ZipEntryReaderUnitTest {
@Test
public void givenZipFile_thenReadEntriesAndValidateContent() throws URISyntaxException, IOException {
Path zipFilePath = Paths.get(getClass().getClassLoader().getResource("zipFile.zip").toURI());
ZipEntryReader.readZipEntries(zipFilePath.toString());
}
}
@@ -3,4 +3,6 @@
- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates)
- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values)
- [Parsing Date Strings with Varying Formats](https://www.baeldung.com/java-parsing-dates-many-formats)
- [How Many Days Are There in a Particular Month of a Given Year?](https://www.baeldung.com/days-particular-month-given-year)
- [Difference Between Instant and LocalDateTime](https://www.baeldung.com/java-instant-vs-localdatetime)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
@@ -0,0 +1,41 @@
package com.baeldung.instantvslocaldatetime;
import org.junit.Test;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class InstantAndLocalDateTimeUnitTest {
@Test
public void givenTwoInstants_whenComparing_thenDifferent() {
// Instant arithmetic
Instant.now().plus(12, ChronoUnit.HOURS);
Instant oneWeekAgo = Instant.now().minus(7, ChronoUnit.DAYS);
// Comparing 2 Instants
Instant instant1 = Instant.now();
Instant instant2 = instant1.plus(1, ChronoUnit.SECONDS);
assertTrue(instant1.isBefore(instant2));
assertFalse(instant1.isAfter(instant2));
}
@Test
public void givenTwoLocalDateTimes_whenComparing_thenDifferent() {
// LocalDateTime arithmetic
LocalDateTime tomorrow = LocalDateTime.now().plus(1, ChronoUnit.DAYS);
LocalDateTime oneYearAgo = LocalDateTime.now().minus(1, ChronoUnit.YEARS);
// Comparing 2 LocalDateTimes
LocalDateTime now = LocalDateTime.now();
LocalDateTime y2k = LocalDateTime.of(2000, 1, 1, 0, 0);
assertTrue(now.isAfter(y2k));
assertTrue(y2k.isBefore(now));
}
}
@@ -7,3 +7,4 @@ This module contains articles about arrays conversion in Java
- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array)
- [Convert a Byte Array to a Numeric Representation in Java](https://www.baeldung.com/java-byte-array-to-number)
- [Converting a String Array Into an int Array in Java](https://www.baeldung.com/java-convert-string-array-to-int-array)
- [Convert Java Array to Iterable](https://www.baeldung.com/java-array-convert-to-iterable)
@@ -0,0 +1,28 @@
package com.baeldung.array.conversions;
import com.google.common.primitives.Ints;
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
import java.util.stream.Collectors;
public class IntArrayToIterableConversionUtils {
public static Iterable<Integer> convertWithStreamToList(int[] array) {
return Arrays.stream(array).boxed().collect(Collectors.toList());
}
public static Iterable<Integer> convertWithStreamIterator(int[] array) {
return () -> Arrays.stream(array).iterator();
}
public static Iterable<Integer> convertWithApacheCommonsAndJavaAsList(int[] array) {
return Arrays.asList(ArrayUtils.toObject(array));
}
public static Iterable<Integer> convertWithGuava(int[] array) {
return Ints.asList(array);
}
}
@@ -0,0 +1,36 @@
package com.baeldung.array.conversions;
import org.junit.jupiter.api.Test;
import static com.baeldung.array.conversions.IntArrayToIterableConversionUtils.*;
import static org.junit.Assert.assertTrue;
class IntArrayToIterableConversionUtilsUnitTest {
private int[] ints = new int[]{1, 2, 3, 4, 5};
@Test
void whenConvertWithStreamToList_thenGetIterable() {
Iterable<Integer> integers = convertWithStreamToList(ints);
assertTrue("should be Iterable", integers instanceof Iterable);
}
@Test
void whenConvertWithStreamIterator_thenGetIterable() {
Iterable<Integer> integers = convertWithStreamIterator(ints);
assertTrue("should be Iterable", integers instanceof Iterable);
}
@Test
void whenConvertWithApacheCommonsAndJavaAsList_thenGetIterable() {
Iterable<Integer> integers = convertWithApacheCommonsAndJavaAsList(ints);
assertTrue("should be Iterable", integers instanceof Iterable);
}
@Test
void whenConvertWithGuava_thenGetIterable() {
Iterable<Integer> integers = convertWithGuava(ints);
assertTrue("should be Iterable", integers instanceof Iterable);
}
}
@@ -12,3 +12,4 @@ This module contains articles about advanced operations on arrays in Java. They
- [Concatenate Two Arrays in Java](https://www.baeldung.com/java-concatenate-arrays)
- [Performance of System.arraycopy() vs. Arrays.copyOf()](https://www.baeldung.com/java-system-arraycopy-arrays-copyof-performance)
- [Slicing Arrays in Java](https://www.baeldung.com/java-slicing-arrays)
- [Combining Two or More Byte Arrays](https://www.baeldung.com/java-concatenate-byte-arrays)
@@ -4,3 +4,4 @@ This module contains articles about Java Booleans.
### Relevant Articles:
- [Convert Boolean to String in Java](https://www.baeldung.com/java-convert-boolean-to-string)
- [Difference Between Boolean.TRUE and true in Java](https://www.baeldung.com/java-boolean-true-primitive-vs-constant)
@@ -0,0 +1,34 @@
package com.baeldung.booleans;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BooleanTrueVsTrueUnitTest {
@Test
public void given_BooleanValues_whenUsingBooleanTrue_thenTestBooleanEquality() {
assertEquals(Boolean.TRUE, Boolean.valueOf(true));
}
@Test
public void given_BooleanValues_whenUsingBooleanTrue_thenTestBooleanIdentity() {
assertTrue(Boolean.TRUE == Boolean.valueOf(true));
}
@Test
public void given_TrueValue_whenUsingTrue_thenTestPrimitiveEquality() {
assertTrue(true == true);
}
@Test
public void given_TrueStringValue_whenUsingBooleanTrue_thenTestBooleanToString() {
assertEquals("true", Boolean.TRUE.toString());
}
@Test
public void given_PrimitiveValue_whenUsingStringValueOf_thenTestPrimitiveToString() {
assertEquals("true", String.valueOf(true));
}
}
@@ -11,4 +11,5 @@ This module contains articles about conversions among Collection types and array
- [Iterate Over a Set in Java](https://www.baeldung.com/java-iterate-set)
- [Convert a List of Integers to a List of Strings](https://www.baeldung.com/java-convert-list-integers-to-list-strings)
- [Combining Two Lists Into a Map in Java](https://www.baeldung.com/java-combine-two-lists-into-map)
- [Convert a List of Strings to a List of Integers](https://www.baeldung.com/java-convert-list-strings-to-integers)
- More articles: [[<-- prev]](../core-java-collections-conversions)
@@ -0,0 +1,46 @@
package com.baeldung.strlisttointlist;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
public class StringListToIntListUnitTest {
private final static List<String> STRING_LIST = Arrays.asList("1", "2", "3", "4", "5", "6", "7");
private final static List<Integer> EXPECTED_LIST = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
@Test
void whenUsingStream_thenGetExpectedIntegerList() {
List<Integer> result = STRING_LIST.stream()
.map(Integer::valueOf)
.collect(Collectors.toList());
assertEquals(EXPECTED_LIST, result);
}
@Test
void whenUsingLoop_thenGetExpectedIntegerList() {
List<Integer> result = new ArrayList<>(STRING_LIST.size());
for (String s : STRING_LIST) {
result.add(Integer.valueOf(s));
}
assertEquals(EXPECTED_LIST, result);
}
@Test
void whenUsingGuava_thenGetExpectedIntegerList() {
List<Integer> result = Lists.transform(STRING_LIST, new Function<String, Integer>() {
@Override
public Integer apply(String input) {
return Integer.valueOf(input);
}
});
assertEquals(EXPECTED_LIST, result);
}
}
@@ -10,3 +10,4 @@ This module contains articles about the Java List collection
- [Array vs. List Performance in Java](https://www.baeldung.com/java-array-vs-list-performance)
- [Set Default Value for Elements in List](https://www.baeldung.com/java-list-set-default-values)
- [Get Unique Values From an ArrayList In Java](https://www.baeldung.com/java-unique-values-arraylist)
- [Converting a Java List to a Json Array](https://www.baeldung.com/java-converting-list-to-json-array)
@@ -0,0 +1,14 @@
package com.baeldung.concurrent.parallel;
import java.io.IOException;
class Benchmark {
public static void main(String[] args) {
try {
org.openjdk.jmh.Main.main(new String[]{"com.baeldung.concurrent.parallel.Processor"});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,73 @@
package com.baeldung.concurrent.parallel;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class Processor {
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void processSerially() throws InterruptedException {
for (int i = 0; i < 100; i++) {
Thread.sleep(10);
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void processParallelyWithExecutorService() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < 100; i++) {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, executorService);
futures.add(future);
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
executorService.shutdown();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void processParallelyWithStream() {
IntStream.range(0, 100)
.parallel()
.forEach(i -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void processParallelyWithStreamSupport() {
Iterable<Integer> iterable = () -> IntStream.range(0, 100).iterator();
Stream<Integer> stream = StreamSupport.stream(iterable.spliterator(), true);
stream.forEach(i -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
@@ -17,22 +17,21 @@ public class Consumer implements Runnable {
public void consume() {
while (dataQueue.runFlag) {
synchronized (dataQueue) {
while (dataQueue.isEmpty() && dataQueue.runFlag) {
try {
dataQueue.waitOnEmpty();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
if (!dataQueue.runFlag) {
while (dataQueue.isEmpty() && dataQueue.runFlag) {
try {
dataQueue.waitOnEmpty();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
Message message = dataQueue.remove();
dataQueue.notifyAllForFull();
useMessage(message);
}
if (!dataQueue.runFlag) {
break;
}
Message message = dataQueue.remove();
dataQueue.notifyAllForFull();
useMessage(message);
}
log.info("Consumer Stopped");
}
@@ -40,7 +39,7 @@ public class Consumer implements Runnable {
private void useMessage(Message message) {
if (message != null) {
log.info(String.format("[%s] Consuming Message. Id: %d, Data: %f%n",
Thread.currentThread().getName(), message.getId(), message.getData()));
Thread.currentThread().getName(), message.getId(), message.getData()));
//Sleeping on random time to make it realistic
ThreadUtil.sleep((long) (message.getData() * 100));
@@ -19,22 +19,21 @@ public class Producer implements Runnable {
public void produce() {
while (dataQueue.runFlag) {
synchronized (dataQueue) {
while (dataQueue.isFull() && dataQueue.runFlag) {
try {
dataQueue.waitOnFull();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
if (!dataQueue.runFlag) {
while (dataQueue.isFull() && dataQueue.runFlag) {
try {
dataQueue.waitOnFull();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
Message message = generateMessage();
dataQueue.add(message);
dataQueue.notifyAllForEmpty();
}
if (!dataQueue.runFlag) {
break;
}
Message message = generateMessage();
dataQueue.add(message);
dataQueue.notifyAllForEmpty();
}
log.info("Producer Stopped");
}
@@ -42,7 +41,7 @@ public class Producer implements Runnable {
private Message generateMessage() {
Message message = new Message(incrementAndGetId(), Math.random());
log.info(String.format("[%s] Generated Message. Id: %d, Data: %f%n",
Thread.currentThread().getName(), message.getId(), message.getData()));
Thread.currentThread().getName(), message.getId(), message.getData()));
//Sleeping on random time to make it realistic
ThreadUtil.sleep((long) (message.getData() * 100));
@@ -0,0 +1,28 @@
package com.baeldung.concurrent.completablefuture.threadpool;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
public class CustomCompletableFuture<T> extends CompletableFuture<T> {
private static final Executor executor = Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "Custom-Single-Thread"));
public static <TYPE> CustomCompletableFuture<TYPE> supplyAsync(Supplier<TYPE> supplier) {
CustomCompletableFuture<TYPE> future = new CustomCompletableFuture<>();
executor.execute(() -> {
try {
future.complete(supplier.get());
} catch (Exception ex) {
future.completeExceptionally(ex);
}
});
return future;
}
@Override
public Executor defaultExecutor() {
return executor;
}
}
@@ -0,0 +1,88 @@
package com.baeldung.concurrent.completablefuture.threadpool;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.Test;
public class CompletableFutureThreadPoolUnitTest {
@Test
void whenUsingNonAsync_thenUsesMainThread() throws ExecutionException, InterruptedException {
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung");
CompletableFuture<Integer> nameLength = name.thenApply(value -> {
printCurrentThread();
return value.length();
});
assertThat(nameLength.get()).isEqualTo(8);
}
@Test
void whenUsingNonAsync_thenUsesCallersThread() throws InterruptedException {
Runnable test = () -> {
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung");
CompletableFuture<Integer> nameLength = name.thenApply(value -> {
printCurrentThread();
return value.length();
});
try {
assertThat(nameLength.get()).isEqualTo(8);
} catch (Exception e) {
fail(e.getMessage());
}
};
new Thread(test, "test-thread").start();
Thread.sleep(100l);
}
@Test
void whenUsingAsync_thenUsesCommonPool() throws ExecutionException, InterruptedException {
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung");
CompletableFuture<Integer> nameLength = name.thenApplyAsync(value -> {
printCurrentThread();
return value.length();
});
assertThat(nameLength.get()).isEqualTo(8);
}
@Test
void whenUsingAsync_thenUsesCustomExecutor() throws ExecutionException, InterruptedException {
Executor testExecutor = Executors.newFixedThreadPool(5);
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung");
CompletableFuture<Integer> nameLength = name.thenApplyAsync(value -> {
printCurrentThread();
return value.length();
}, testExecutor);
assertThat(nameLength.get()).isEqualTo(8);
}
@Test
void whenOverridingDefaultThreadPool_thenUsesCustomExecutor() throws ExecutionException, InterruptedException {
CompletableFuture<String> name = CustomCompletableFuture.supplyAsync(() -> "Baeldung");
CompletableFuture<Integer> nameLength = name.thenApplyAsync(value -> {
printCurrentThread();
return value.length();
});
assertThat(nameLength.get()).isEqualTo(8);
}
private static void printCurrentThread() {
System.out.println(Thread.currentThread().getName());
}
}
@@ -0,0 +1,112 @@
package com.baeldung.concurrent.anonymousthread;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class AnonymousThreadUnitTest {
static ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
static PrintStream printStream = new PrintStream(outputStream);
static List<String> expectedNumbers = new ArrayList<>();
@BeforeClass
public static void setupClass() {
for (int i = 1; i <= 10; i++) {
expectedNumbers.add(String.valueOf(i));
}
}
@Before
public void setupMethod() {
System.setOut(printStream);
}
@After
public void cleanUpMethod() {
outputStream.reset();
System.setOut(System.out);
}
@AfterClass
public static void cleanupClass() throws IOException {
expectedNumbers.clear();
outputStream.close();
printStream.close();
}
@Test
public void givenAnonymousThreadSubclassOverridingRunMethod_whenStart_thenRunAsExpected() {
Thread anonymousThread = new Thread() {
@Override
public void run() {
printNumbersFrom1To10();
}
};
anonymousThread.start();
waitForThreadToFinish();
anonymousThread.interrupt();
String[] printedNumbers = getPrintedNumbers();
assertEquals(expectedNumbers, List.of(printedNumbers));
}
@Test
public void givenAnonymousThreadWithLambdaExpression_whenStart_thenRunAsExpected() {
Thread anonymousThread = new Thread(() -> {
printNumbersFrom1To10();
});
anonymousThread.start();
waitForThreadToFinish();
anonymousThread.interrupt();
String[] printedNumbers = getPrintedNumbers();
assertEquals(expectedNumbers, List.of(printedNumbers));
}
@Test
public void givenAnonymousThreadWithRunnableObject_whenStart_thenRunAsExpected() {
Thread anonymousThread = new Thread(new Runnable() {
@Override
public void run() {
printNumbersFrom1To10();
}
});
anonymousThread.start();
waitForThreadToFinish();
anonymousThread.interrupt();
String[] printedNumbers = getPrintedNumbers();
assertEquals(expectedNumbers, List.of(printedNumbers));
}
private void printNumbersFrom1To10() {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
private void waitForThreadToFinish() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignore
}
}
private String[] getPrintedNumbers() {
String printedOutput = outputStream.toString()
.trim();
return printedOutput.split(System.lineSeparator());
}
}
@@ -19,6 +19,16 @@
<artifactId>jansi</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
@@ -70,6 +80,16 @@
<target>${target.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<excludeJUnit5Engines>
<engine>junit-vintage-engine</engine>
</excludeJUnit5Engines>
</configuration>
</plugin>
</plugins>
</build>
@@ -1,9 +1,10 @@
package com.baeldung.asciiart;
import com.baeldung.asciiart.AsciiArt.Settings;
import org.junit.Test;
import java.awt.Font;
import java.awt.*;
import org.junit.jupiter.api.Test;
import com.baeldung.asciiart.AsciiArt.Settings;
public class AsciiArtIntegrationTest {
@@ -12,7 +13,7 @@ public class AsciiArtIntegrationTest {
AsciiArt asciiArt = new AsciiArt();
String text = "BAELDUNG";
Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); // 30 pixel width per character
asciiArt.drawString(text, "*", settings);
}
}
@@ -6,4 +6,6 @@ This module contains articles about date operations in Java.
- [Create Date From Unix Timestamp in Java](https://www.baeldung.com/java-date-unix-timestamp)
- [Convert java.util.Date to java.sql.Date](https://www.baeldung.com/java-convert-util-date-to-sql)
- [How to Determine Date of the First Day of the Week Using LocalDate in Java](https://www.baeldung.com/java-first-day-of-the-week)
- [Adding One Month to Current Date in Java](https://www.baeldung.com/java-adding-one-month-to-current-date)
- [How to Get Last Day of a Month in Java](https://www.baeldung.com/java-last-day-month)
- [[<-- Prev]](/core-java-modules/core-java-date-operations-2)
@@ -12,5 +12,23 @@
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
<properties>
<joda-time.version>2.12.5</joda-time.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
</properties>
</project>
@@ -0,0 +1,32 @@
package com.baeldung.lastdaymonth;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
public class LastDayOfMonth {
static int getLastDayOfMonthUsingCalendar(int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, month);
return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
static int getLastDayOfMonthUsingTemporalAdjusters(LocalDate date) {
return date.with(TemporalAdjusters.lastDayOfMonth())
.getDayOfMonth();
}
static int getLastDayOfMonthUsingYearMonth(YearMonth date) {
return date.atEndOfMonth()
.getDayOfMonth();
}
static int getLastDayOfMonthUsingJodaTime(org.joda.time.LocalDate date) {
return date.dayOfMonth()
.withMaximumValue()
.getDayOfMonth();
}
}

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