Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
@@ -1,5 +1,3 @@
|
||||
**UPDATE**: The price of "Learn Spring Security OAuth" will permanently change on the 11th of December, along with the upcoming OAuth2 material: http://bit.ly/github-lss
|
||||
|
||||
The Courses
|
||||
==============================
|
||||
|
||||
|
||||
@@ -5,6 +5,6 @@ This module contains articles about genetic algorithms.
|
||||
### Relevant articles:
|
||||
|
||||
- [Introduction to Jenetics Library](https://www.baeldung.com/jenetics)
|
||||
- [Ant Colony Optimization](https://www.baeldung.com/java-ant-colony-optimization)
|
||||
- [Ant Colony Optimization with a Java Example](https://www.baeldung.com/java-ant-colony-optimization)
|
||||
- [Design a Genetic Algorithm in Java](https://www.baeldung.com/java-genetic-algorithm)
|
||||
- [The Traveling Salesman Problem in Java](https://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||
|
||||
@@ -6,8 +6,8 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
### Relevant articles:
|
||||
|
||||
- [Validating Input With Finite Automata in Java](https://www.baeldung.com/java-finite-automata)
|
||||
- [Example of Hill Climbing Algorithm](https://www.baeldung.com/java-hill-climbing-algorithm)
|
||||
- [Introduction to Minimax Algorithm](https://www.baeldung.com/java-minimax-algorithm)
|
||||
- [Example of Hill Climbing Algorithm in Java](https://www.baeldung.com/java-hill-climbing-algorithm)
|
||||
- [Introduction to Minimax Algorithm with a Java Implementation](https://www.baeldung.com/java-minimax-algorithm)
|
||||
- [How to Calculate Levenshtein Distance in Java?](https://www.baeldung.com/java-levenshtein-distance)
|
||||
- [How to Find the Kth Largest Element in Java](https://www.baeldung.com/java-kth-largest-element)
|
||||
- More articles: [[next -->]](/algorithms-miscellaneous-2)
|
||||
|
||||
@@ -5,8 +5,8 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
### Relevant articles:
|
||||
|
||||
- [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm)
|
||||
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Find the Middle Element of a Linked List](https://www.baeldung.com/java-linked-list-middle-element)
|
||||
- [Check If a String Contains All The Letters of The Alphabet with Java](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Find the Middle Element of a Linked List in Java](https://www.baeldung.com/java-linked-list-middle-element)
|
||||
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
||||
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
||||
|
||||
@@ -9,11 +9,11 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
|
||||
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
|
||||
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
|
||||
- [How to Determine if a Binary Tree is Balanced](https://www.baeldung.com/java-balanced-binary-tree)
|
||||
- [How to Determine if a Binary Tree is Balanced in Java](https://www.baeldung.com/java-balanced-binary-tree)
|
||||
- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
|
||||
- [Prim’s Algorithm](https://www.baeldung.com/java-prim-algorithm)
|
||||
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray)
|
||||
- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays)
|
||||
- [Median of Stream of Integers using Heap](https://www.baeldung.com/java-stream-integers-median-using-heap)
|
||||
- [Prim’s Algorithm with a Java Implementation](https://www.baeldung.com/java-prim-algorithm)
|
||||
- [Maximum Subarray Problem in Java](https://www.baeldung.com/java-maximum-subarray)
|
||||
- [How to Merge Two Sorted Arrays in Java](https://www.baeldung.com/java-merge-sorted-arrays)
|
||||
- [Median of Stream of Integers using Heap in Java](https://www.baeldung.com/java-stream-integers-median-using-heap)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-4) [[next -->]](/algorithms-miscellaneous-6)
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Boruvka’s Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm)
|
||||
- [Boruvka’s Algorithm for Minimum Spanning Trees in Java](https://www.baeldung.com/java-boruvka-algorithm)
|
||||
- [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent)
|
||||
- [Kruskal’s Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal)
|
||||
- [Kruskal’s Algorithm for Spanning Trees with a Java Implementation](https://www.baeldung.com/java-spanning-trees-kruskal)
|
||||
- [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm)
|
||||
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
|
||||
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
|
||||
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
|
||||
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
|
||||
- [Finding Top K Elements in an Array](https://www.baeldung.com/java-array-top-elements)
|
||||
- [Finding Top K Elements in a Java Array](https://www.baeldung.com/java-array-top-elements)
|
||||
- [Reversing a Linked List in Java](https://www.baeldung.com/java-reverse-linked-list)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-5)
|
||||
|
||||
@@ -8,8 +8,8 @@ This module contains articles about searching algorithms.
|
||||
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)
|
||||
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
|
||||
- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search)
|
||||
- [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
|
||||
- [String Search Algorithms for Large Texts with Java](https://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game in Java](https://www.baeldung.com/java-monte-carlo-tree-search)
|
||||
- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search)
|
||||
- [Fast Pattern Matching of Strings Using Suffix Tree](https://www.baeldung.com/java-pattern-matching-suffix-tree)
|
||||
- [Find the Kth Smallest Element in Two Sorted Arrays](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)
|
||||
- [Fast Pattern Matching of Strings Using Suffix Tree in Java](https://www.baeldung.com/java-pattern-matching-suffix-tree)
|
||||
- [Find the Kth Smallest Element in Two Sorted Arrays in Java](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
|
||||
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
|
||||
- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers)
|
||||
- [How an In-Place Sorting Algorithm Works](https://www.baeldung.com/java-in-place-sorting)
|
||||
- [Partitioning and Sorting Arrays with Many Repeated Entries](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)
|
||||
- [Guide to In-Place Sorting Algorithm Works with a Java Implementation](https://www.baeldung.com/java-in-place-sorting)
|
||||
- [Partitioning and Sorting Arrays with Many Repeated Entries with Java Examples](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)
|
||||
- More articles: [[<-- prev]](/algorithms-sorting)
|
||||
|
||||
@@ -8,3 +8,4 @@ This module contains articles about Apache Spark
|
||||
- [Building a Data Pipeline with Kafka, Spark Streaming and Cassandra](https://www.baeldung.com/kafka-spark-data-pipeline)
|
||||
- [Machine Learning with Spark MLlib](https://www.baeldung.com/spark-mlib-machine-learning)
|
||||
- [Introduction to Spark Graph Processing with GraphFrames](https://www.baeldung.com/spark-graph-graphframes)
|
||||
- [Apache Spark: Differences between Dataframes, Datasets and RDDs](https://www.baeldung.com/java-spark-dataframe-dataset-rdd)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
--enable-preview
|
||||
@@ -0,0 +1,7 @@
|
||||
## Core Java 15
|
||||
|
||||
This module contains articles about Java 15.
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- TODO: add article links here
|
||||
@@ -0,0 +1,77 @@
|
||||
<?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-15</artifactId>
|
||||
<name>core-java-15</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>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${apache-commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit-jupiter.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>
|
||||
<release>${maven.compiler.release}</release>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
<source>15</source>
|
||||
<target>15</target>
|
||||
</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.release>15</maven.compiler.release>
|
||||
<apache-commons-lang3.version>3.11</apache-commons-lang3.version>
|
||||
<assertj.version>3.17.2</assertj.version>
|
||||
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
||||
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.sealed.alternative;
|
||||
|
||||
public class Vehicles {
|
||||
|
||||
abstract static class Vehicle {
|
||||
|
||||
private final String registrationNumber;
|
||||
|
||||
public Vehicle(String registrationNumber) {
|
||||
this.registrationNumber = registrationNumber;
|
||||
}
|
||||
|
||||
public String getRegistrationNumber() {
|
||||
return registrationNumber;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static final class Car extends Vehicle {
|
||||
|
||||
private final int numberOfSeats;
|
||||
|
||||
public Car(int numberOfSeats, String registrationNumber) {
|
||||
super(registrationNumber);
|
||||
this.numberOfSeats = numberOfSeats;
|
||||
}
|
||||
|
||||
public int getNumberOfSeats() {
|
||||
return numberOfSeats;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static final class Truck extends Vehicle {
|
||||
|
||||
private final int loadCapacity;
|
||||
|
||||
public Truck(int loadCapacity, String registrationNumber) {
|
||||
super(registrationNumber);
|
||||
this.loadCapacity = loadCapacity;
|
||||
}
|
||||
|
||||
public int getLoadCapacity() {
|
||||
return loadCapacity;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.sealed.classes;
|
||||
|
||||
public non-sealed class Car extends Vehicle implements Service {
|
||||
|
||||
private final int numberOfSeats;
|
||||
|
||||
public Car(int numberOfSeats, String registrationNumber) {
|
||||
super(registrationNumber);
|
||||
this.numberOfSeats = numberOfSeats;
|
||||
}
|
||||
|
||||
public int getNumberOfSeats() {
|
||||
return numberOfSeats;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMaxServiceIntervalInMonths() {
|
||||
return 12;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.sealed.classes;
|
||||
|
||||
public sealed interface Service permits Car, Truck {
|
||||
|
||||
int getMaxServiceIntervalInMonths();
|
||||
|
||||
default int getMaxDistanceBetweenServicesInKilometers() {
|
||||
return 100000;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.sealed.classes;
|
||||
|
||||
public final class Truck extends Vehicle implements Service {
|
||||
|
||||
private final int loadCapacity;
|
||||
|
||||
public Truck(int loadCapacity, String registrationNumber) {
|
||||
super(registrationNumber);
|
||||
this.loadCapacity = loadCapacity;
|
||||
}
|
||||
|
||||
public int getLoadCapacity() {
|
||||
return loadCapacity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMaxServiceIntervalInMonths() {
|
||||
return 18;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.sealed.classes;
|
||||
|
||||
public abstract sealed class Vehicle permits Car, Truck {
|
||||
|
||||
protected final String registrationNumber;
|
||||
|
||||
public Vehicle(String registrationNumber) {
|
||||
this.registrationNumber = registrationNumber;
|
||||
}
|
||||
|
||||
public String getRegistrationNumber() {
|
||||
return registrationNumber;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.sealed.records;
|
||||
|
||||
public record Car(int numberOfSeats, String registrationNumber) implements Vehicle {
|
||||
|
||||
@Override
|
||||
public String getRegistrationNumber() {
|
||||
return registrationNumber;
|
||||
}
|
||||
|
||||
public int getNumberOfSeats() {
|
||||
return numberOfSeats;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.sealed.records;
|
||||
|
||||
public record Truck(int loadCapacity, String registrationNumber) implements Vehicle {
|
||||
|
||||
@Override
|
||||
public String getRegistrationNumber() {
|
||||
return registrationNumber;
|
||||
}
|
||||
|
||||
public int getLoadCapacity() {
|
||||
return loadCapacity;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.sealed.records;
|
||||
|
||||
public sealed interface Vehicle permits Car, Truck {
|
||||
|
||||
String getRegistrationNumber();
|
||||
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.sealed.classes;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.constant.ClassDesc;
|
||||
|
||||
public class VehicleUnitTest {
|
||||
|
||||
private static Vehicle car;
|
||||
private static Vehicle truck;
|
||||
|
||||
@BeforeAll
|
||||
public static void createInstances() {
|
||||
car = new Car(5, "VZ500DA");
|
||||
truck = new Truck(19000, "VZ600TA");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenUsingReflectionAPI_thenSuperClassIsSealed() {
|
||||
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(car.getClass().getSuperclass().isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(car.getClass().getSuperclass().permittedSubclasses())
|
||||
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenUsingReflectionAPI_thenSuperClassIsSealed() {
|
||||
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(truck.getClass().getSuperclass().isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(truck.getClass().getSuperclass().permittedSubclasses())
|
||||
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenGettingPropertyTraditionalWay_thenNumberOfSeatsPropertyIsReturned() {
|
||||
Assertions.assertThat(getPropertyTraditionalWay(car)).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenGettingPropertyViaPatternMatching_thenNumberOfSeatsPropertyIsReturned() {
|
||||
Assertions.assertThat(getPropertyViaPatternMatching(car)).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenGettingPropertyTraditionalWay_thenLoadCapacityIsReturned() {
|
||||
Assertions.assertThat(getPropertyTraditionalWay(truck)).isEqualTo(19000);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenGettingPropertyViaPatternMatching_thenLoadCapacityIsReturned() {
|
||||
Assertions.assertThat(getPropertyViaPatternMatching(truck)).isEqualTo(19000);
|
||||
}
|
||||
|
||||
private int getPropertyTraditionalWay(Vehicle vehicle) {
|
||||
if (vehicle instanceof Car) {
|
||||
return ((Car) vehicle).getNumberOfSeats();
|
||||
} else if (vehicle instanceof Truck) {
|
||||
return ((Truck) vehicle).getLoadCapacity();
|
||||
} else {
|
||||
throw new RuntimeException("Unknown instance of Vehicle");
|
||||
}
|
||||
}
|
||||
|
||||
private int getPropertyViaPatternMatching(Vehicle vehicle) {
|
||||
if (vehicle instanceof Car car) {
|
||||
return car.getNumberOfSeats();
|
||||
} else if (vehicle instanceof Truck truck) {
|
||||
return truck.getLoadCapacity();
|
||||
} else {
|
||||
throw new RuntimeException("Unknown instance of Vehicle");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.sealed.records;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.constant.ClassDesc;
|
||||
|
||||
public class VehicleUnitTest {
|
||||
|
||||
private static Vehicle car;
|
||||
private static Vehicle truck;
|
||||
|
||||
@BeforeAll
|
||||
public static void createInstances() {
|
||||
car = new Car(4, "VZ500DA");
|
||||
truck = new Truck(16000, "VZ600TA");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenUsingReflectionAPI_thenInterfaceIsSealed() {
|
||||
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(car.getClass().getInterfaces()[0].isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(car.getClass().getInterfaces()[0].permittedSubclasses())
|
||||
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenUsingReflectionAPI_thenInterfaceIsSealed() {
|
||||
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(truck.getClass().getInterfaces()[0].isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(truck.getClass().getInterfaces()[0].permittedSubclasses())
|
||||
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenGettingPropertyTraditionalWay_thenNumberOfSeatsPropertyIsReturned() {
|
||||
Assertions.assertThat(getPropertyTraditionalWay(car)).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenGettingPropertyViaPatternMatching_thenNumberOfSeatsPropertyIsReturned() {
|
||||
Assertions.assertThat(getPropertyViaPatternMatching(car)).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenGettingPropertyTraditionalWay_thenLoadCapacityIsReturned() {
|
||||
Assertions.assertThat(getPropertyTraditionalWay(truck)).isEqualTo(16000);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenGettingPropertyViaPatternMatching_thenLoadCapacityIsReturned() {
|
||||
Assertions.assertThat(getPropertyViaPatternMatching(truck)).isEqualTo(16000);
|
||||
}
|
||||
|
||||
private int getPropertyTraditionalWay(Vehicle vehicle) {
|
||||
if (vehicle instanceof Car) {
|
||||
return ((Car) vehicle).getNumberOfSeats();
|
||||
} else if (vehicle instanceof Truck) {
|
||||
return ((Truck) vehicle).getLoadCapacity();
|
||||
} else {
|
||||
throw new RuntimeException("Unknown instance of Vehicle");
|
||||
}
|
||||
}
|
||||
|
||||
private int getPropertyViaPatternMatching(Vehicle vehicle) {
|
||||
if (vehicle instanceof Car car) {
|
||||
return car.getNumberOfSeats();
|
||||
} else if (vehicle instanceof Truck truck) {
|
||||
return truck.getLoadCapacity();
|
||||
} else {
|
||||
throw new RuntimeException("Unknown instance of Vehicle");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -14,3 +14,4 @@
|
||||
- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list)
|
||||
- [A Guide to BitSet in Java](https://www.baeldung.com/java-bitset)
|
||||
- [Get the First Key and Value From a HashMap](https://www.baeldung.com/java-hashmap-get-first-entry)
|
||||
- [Performance of removeAll() in a HashSet](https://www.baeldung.com/java-hashset-removeall-performance)
|
||||
|
||||
@@ -13,7 +13,7 @@ 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 Lock-Free Data Structures with Java Examples](https://www.baeldung.com/lock-free-programming)
|
||||
- [Introduction to Exchanger in Java](https://www.baeldung.com/java-exchanger)
|
||||
- [Why Not To Start A Thread In The Constructor?](https://www.baeldung.com/java-thread-constructor)
|
||||
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)
|
||||
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
package com.baeldung.concurrent.stopexecution;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
public class StopExecution {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(StopExecution.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
StopExecution stopExecution = new StopExecution();
|
||||
//stopExecution.testUsingLoop();
|
||||
//stopExecution.testTimer();
|
||||
stopExecution.testScheduledExecutor();
|
||||
LOG.info("done");
|
||||
}
|
||||
|
||||
public void testUsingLoop() {
|
||||
long start = System.currentTimeMillis();
|
||||
long end = start + 5000;
|
||||
List<String> items = new ArrayList<>();
|
||||
int counter = 0;
|
||||
|
||||
// Let this loop run only upto 5 seconds
|
||||
while (System.currentTimeMillis() < end && counter < items.size()) {
|
||||
// Fetch the item from the list.
|
||||
// Some expensive operation on the item.
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
|
||||
public static void testThreads() {
|
||||
Thread thread = new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
LOG.info("inside run");
|
||||
|
||||
try {
|
||||
Thread.sleep(10000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
LOG.info("exit run");
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
while (thread.getState() != Thread.State.TERMINATED) {
|
||||
LOG.info(thread.getState().name());
|
||||
try {
|
||||
Thread.sleep(500);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void testExecutor() {
|
||||
final ExecutorService service = Executors.newSingleThreadExecutor();
|
||||
Future<String> f = null;
|
||||
try {
|
||||
f = service.submit(() -> {
|
||||
// Do you long running calculation here
|
||||
try {
|
||||
Thread.sleep(2737); // Simulate some delay
|
||||
} catch (InterruptedException e) {
|
||||
LOG.info("Interrupted");
|
||||
return "interrupted";
|
||||
}
|
||||
LOG.info("Sleep finished");
|
||||
return "42";
|
||||
});
|
||||
|
||||
LOG.info(f.get(2, TimeUnit.SECONDS));
|
||||
} catch (TimeoutException e) {
|
||||
f.cancel(true);
|
||||
LOG.error("Calculation took to long");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
service.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
public void testExecutor2() {
|
||||
final ExecutorService service = Executors.newSingleThreadExecutor();
|
||||
Future f = null;
|
||||
try {
|
||||
f = service.submit(new LongRunningTask());
|
||||
LOG.info("testExecutor2");
|
||||
f.get(1, TimeUnit.SECONDS);
|
||||
} catch (final TimeoutException e) {
|
||||
f.cancel(true);
|
||||
LOG.error("Calculation took to long");
|
||||
} catch (final Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
service.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
public void testScheduledExecutor() {
|
||||
LOG.info("testScheduledExecutor");
|
||||
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
|
||||
Future future = executor.submit(new LongRunningTask());
|
||||
executor.schedule(new Runnable() {
|
||||
public void run() {
|
||||
future.cancel(true);
|
||||
}
|
||||
}, 1000, TimeUnit.MILLISECONDS);
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
public void testThreadAndInterrupt() {
|
||||
|
||||
Thread t;
|
||||
try {
|
||||
t = new Thread(new LongRunningTask());
|
||||
|
||||
LOG.info("testExecutor3");
|
||||
long end = System.currentTimeMillis() + 2000;
|
||||
t.start();
|
||||
while (t.isAlive() && System.currentTimeMillis() < end) {
|
||||
Thread.sleep(50);
|
||||
}
|
||||
t.interrupt();
|
||||
} catch (final Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void testTimer() {
|
||||
LOG.info("Timer test");
|
||||
Thread t = new Thread(new LongRunningTask());
|
||||
Timer timeoutTimer = new Timer();
|
||||
timeoutTimer.schedule(new TimeOutTask(t, timeoutTimer), 1000);
|
||||
t.start();
|
||||
}
|
||||
|
||||
class MyRunnableTask implements Runnable {
|
||||
public void run() {
|
||||
try {
|
||||
LOG.info("MyRunnable...");
|
||||
Thread.sleep(10000);
|
||||
} catch (InterruptedException ie) {
|
||||
LOG.info("MyRunnable interrupted...");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class TimeOutTask extends TimerTask {
|
||||
private Thread t;
|
||||
private Timer timer;
|
||||
|
||||
TimeOutTask(Thread t, Timer timer) {
|
||||
this.t = t;
|
||||
this.timer = timer;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
if (t != null && t.isAlive()) {
|
||||
t.interrupt();
|
||||
timer.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class LongRunningTask implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
longRunningSort();
|
||||
}
|
||||
|
||||
private void longRunningOperation() {
|
||||
LOG.info("long Running operation started");
|
||||
|
||||
try {
|
||||
//Thread.sleep(500);
|
||||
longFileRead();
|
||||
LOG.info("long running operation finished");
|
||||
} catch (InterruptedException e) {
|
||||
LOG.info("long Running operation interrupted");
|
||||
}
|
||||
}
|
||||
|
||||
private void longRunningSort() {
|
||||
LOG.info("long Running task started");
|
||||
// Do you long running calculation here
|
||||
int len = 100000;
|
||||
List<Integer> numbers = new ArrayList<>();
|
||||
try {
|
||||
for (int i = len; i > 0; i--) {
|
||||
//Thread.sleep(5)
|
||||
numbers.add(i);
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
for (i = 0; i < len; i++) {
|
||||
int minIndex = i;
|
||||
for (int j = i + 1; j < len; j++) {
|
||||
if (numbers.get(minIndex) > numbers.get(j))
|
||||
minIndex = j;
|
||||
}
|
||||
if (minIndex != i) {
|
||||
int temp = numbers.get(i);
|
||||
numbers.set(i, numbers.get(minIndex));
|
||||
numbers.set(minIndex, temp);
|
||||
}
|
||||
throwExceptionOnThreadInterrupt();
|
||||
}
|
||||
LOG.info("Index position: " + i);
|
||||
LOG.info("Long running task finished");
|
||||
} catch (InterruptedException e) {
|
||||
LOG.info("long Running operation interrupted");
|
||||
}
|
||||
}
|
||||
|
||||
private void longFileRead() throws InterruptedException {
|
||||
String file = "input.txt";
|
||||
ClassLoader classloader = getClass().getClassLoader();
|
||||
|
||||
try (InputStream inputStream = classloader.getResourceAsStream(file)) {
|
||||
Reader inputStreamReader = new InputStreamReader(inputStream);
|
||||
|
||||
int data = inputStreamReader.read();
|
||||
while (data != -1) {
|
||||
char theChar = (char) data;
|
||||
data = inputStreamReader.read();
|
||||
throwExceptionOnThreadInterrupt();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.error("Exception: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void throwExceptionOnThreadInterrupt() throws InterruptedException {
|
||||
if (Thread.currentThread().interrupted()) {
|
||||
throw new InterruptedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,14 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>1.4.191</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.exceptions.abstractmethoderror;
|
||||
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
class AbstractMethodErrorUnitTest {
|
||||
private static final String url = "jdbc:h2:mem:A-DATABASE;INIT=CREATE SCHEMA IF NOT EXISTS myschema";
|
||||
private static final String username = "sa";
|
||||
|
||||
@Test
|
||||
void givenOldH2Database_whenCallgetSchemaMethod_thenThrowAbstractMethodError() throws SQLException {
|
||||
Connection conn = DriverManager.getConnection(url, username, "");
|
||||
assertNotNull(conn);
|
||||
Assertions.assertThrows(AbstractMethodError.class, () -> conn.getSchema());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
## Relevant articles:
|
||||
@@ -0,0 +1,18 @@
|
||||
<?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-functional</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-functional</name>
|
||||
<packaging>jar</packaging>
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
</project>
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.functional;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class Currying {
|
||||
|
||||
private static Function<Double, Function<Double, Double>> weight = mass -> gravity -> mass * gravity;
|
||||
|
||||
private static Function<Double, Double> weightOnEarth = weight.apply(9.81);
|
||||
|
||||
private static Function<Double, Double> weightOnMars = weight.apply(3.75);
|
||||
|
||||
public static Double weightOnEarth(Double mass) {
|
||||
return weightOnEarth.apply(mass);
|
||||
}
|
||||
|
||||
public static Double weightOnMars(Double mass) {
|
||||
return weightOnMars.apply(mass);
|
||||
}
|
||||
|
||||
public static Function<Double, Double> weightOnEarth() {
|
||||
final double gravity = 9.81;
|
||||
return mass -> mass * gravity;
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user