Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
2d2f29b524
@ -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)
|
||||
|
@ -51,7 +51,7 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
<scope>provided</scope>
|
||||
<exclusions>
|
||||
|
@ -89,7 +89,6 @@
|
||||
|
||||
<properties>
|
||||
<json-simple.version>1.1.1</json-simple.version>
|
||||
<commons-io.version>2.5</commons-io.version>
|
||||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
||||
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
|
@ -6,10 +6,12 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
|
||||
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistry;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@ -22,11 +24,14 @@ import static org.hibernate.cfg.AvailableSettings.PASS;
|
||||
*/
|
||||
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
private SessionFactory sessionFactory = createSessionFactory();
|
||||
|
||||
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
|
||||
try (SessionFactory sessionFactory = createSessionFactory()) {
|
||||
try {
|
||||
ShippingService service = new ShippingService(sessionFactory, new ShippingDao());
|
||||
return routeRequest(input, service);
|
||||
} finally {
|
||||
flushConnectionPool();
|
||||
}
|
||||
}
|
||||
|
||||
@ -105,4 +110,12 @@ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
.buildMetadata()
|
||||
.buildSessionFactory();
|
||||
}
|
||||
|
||||
private void flushConnectionPool() {
|
||||
ConnectionProvider connectionProvider = sessionFactory.getSessionFactoryOptions()
|
||||
.getServiceRegistry()
|
||||
.getService(ConnectionProvider.class);
|
||||
HikariDataSource hikariDataSource = connectionProvider.unwrap(HikariDataSource.class);
|
||||
hikariDataSource.getHikariPoolMXBean().softEvictConnections();
|
||||
}
|
||||
}
|
||||
|
@ -154,7 +154,6 @@
|
||||
<properties>
|
||||
<blade-mvc.version>2.0.14.RELEASE</blade-mvc.version>
|
||||
<bootstrap.version>4.2.1</bootstrap.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<lombok.version>1.18.4</lombok.version>
|
||||
<httpclient.version>4.5.6</httpclient.version>
|
||||
<httpmime.version>4.5.6</httpmime.version>
|
||||
|
@ -5,8 +5,9 @@ This module contains articles about Java 10 core features
|
||||
### Relevant Articles:
|
||||
|
||||
- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference)
|
||||
- [Guide to Java 10](http://www.baeldung.com/java-10-overview)
|
||||
- [New Features in Java 10](https://www.baeldung.com/java-10-overview)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler)
|
||||
- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets)
|
||||
- [Converting between a List and a Set in Java](https://www.baeldung.com/convert-list-to-set-and-set-to-list)
|
||||
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)
|
||||
|
@ -6,3 +6,4 @@ This module contains articles about Java 11 core features
|
||||
- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional)
|
||||
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
||||
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
|
||||
|
@ -28,6 +28,29 @@
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mock-server</groupId>
|
||||
<artifactId>mockserver-junit-jupiter</artifactId>
|
||||
<version>${mockserver.version}</version>
|
||||
</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-params</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>
|
||||
@ -48,7 +71,9 @@
|
||||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<guava.version>29.0-jre</guava.version>
|
||||
<junit.jupiter.version>5.7.0</junit.jupiter.version>
|
||||
<assertj.version>3.17.2</assertj.version>
|
||||
<mockserver.version>5.11.1</mockserver.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
public class MainClass {
|
||||
|
||||
private static boolean mainPrivateMethod() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static class NestedClass {
|
||||
|
||||
boolean nestedPublicMethod() {
|
||||
return mainPrivateMethod();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockserver.integration.ClientAndServer;
|
||||
import org.mockserver.model.HttpStatusCode;
|
||||
import org.mockserver.socket.PortFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
|
||||
class HttpClientIntegrationTest {
|
||||
|
||||
private static ClientAndServer mockServer;
|
||||
private static int port;
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() {
|
||||
port = PortFactory.findFreePort();
|
||||
mockServer = startClientAndServer(port);
|
||||
mockServer.when(new org.mockserver.model.HttpRequest().withMethod("GET"))
|
||||
.respond(new org.mockserver.model.HttpResponse()
|
||||
.withStatusCode(HttpStatusCode.OK_200.code())
|
||||
.withBody("Hello from the server!"));
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
mockServer.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSampleHttpRequest_whenRequestIsSent_thenServerResponseIsReceived() throws IOException, InterruptedException {
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.connectTimeout(Duration.ofSeconds(20))
|
||||
.build();
|
||||
HttpRequest httpRequest = HttpRequest.newBuilder()
|
||||
.GET()
|
||||
.uri(URI.create("http://localhost:" + port))
|
||||
.build();
|
||||
HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
|
||||
assertThat(httpResponse.body()).isEqualTo("Hello from the server!");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class JavaElevenFeaturesUnitTest {
|
||||
|
||||
@Test
|
||||
void givenMultilineString_whenExtractingNonBlankStrippedLines_thenLinesAreReturned() {
|
||||
String multilineString = "Baeldung helps \n \n developers \n explore Java.";
|
||||
List<String> lines = multilineString.lines()
|
||||
.filter(line -> !line.isBlank())
|
||||
.map(String::strip)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(lines).containsExactly("Baeldung helps", "developers", "explore Java.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTemporaryFile_whenReadingStringContent_thenContentIsReturned(@TempDir Path tempDir) throws IOException {
|
||||
Path filePath = Files.writeString(Files.createTempFile(tempDir, "demo", ".txt"), "Sample text");
|
||||
String fileContent = Files.readString(filePath);
|
||||
assertThat(fileContent).isEqualTo("Sample text");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSampleList_whenConvertingToArray_thenItemsRemainUnchanged() {
|
||||
List<String> sampleList = Arrays.asList("Java", "Kotlin");
|
||||
String[] sampleArray = sampleList.toArray(String[]::new);
|
||||
assertThat(sampleArray).containsExactly("Java", "Kotlin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSampleList_whenConvertingToUppercaseString_thenUppercaseIsReturned() {
|
||||
List<String> sampleList = Arrays.asList("Java", "Kotlin");
|
||||
String resultString = sampleList.stream()
|
||||
.map((@Nonnull var x) -> x.toUpperCase())
|
||||
.collect(Collectors.joining(", "));
|
||||
assertThat(resultString).isEqualTo("JAVA, KOTLIN");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSampleList_whenExtractingNonBlankValues_thenOnlyNonBlanksAreReturned() {
|
||||
List<String> sampleList = Arrays.asList("Java", "\n \n", "Kotlin", " ");
|
||||
List<String> withoutBlanks = sampleList.stream()
|
||||
.filter(Predicate.not(String::isBlank))
|
||||
.collect(Collectors.toList());
|
||||
assertThat(withoutBlanks).containsExactly("Java", "Kotlin");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class NestedClassesUnitTest {
|
||||
|
||||
@Test
|
||||
public void giveNestedClass_whenCallingMainClassPrivateMethod_thenNoExceptionIsThrown() {
|
||||
MainClass.NestedClass nestedInstance = new MainClass.NestedClass();
|
||||
assertThat(nestedInstance.nestedPublicMethod()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveNestedClass_whenCheckingNestmate_thenNestedClassIsReturned() {
|
||||
assertThat(MainClass.class.isNestmateOf(MainClass.NestedClass.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveNestedClass_whenCheckingNestHost_thenMainClassIsReturned() {
|
||||
assertThat(MainClass.NestedClass.class.getNestHost()).isEqualTo(MainClass.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveNestedClass_whenCheckingNestMembers_thenNestMembersAreReturned() {
|
||||
Set<String> nestedMembers = Arrays.stream(MainClass.NestedClass.class.getNestMembers())
|
||||
.map(Class::getName)
|
||||
.collect(Collectors.toSet());
|
||||
assertThat(nestedMembers).contains(MainClass.class.getName(), MainClass.NestedClass.class.getName());
|
||||
}
|
||||
|
||||
}
|
@ -64,7 +64,7 @@ public class HttpClientUnitTest {
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
|
||||
assertThat(response.body(), containsString("https://stackoverflow.com/"));
|
||||
assertTrue(response.headers().map().get("location").stream().anyMatch("https://stackoverflow.com/"::equals));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -18,6 +18,7 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
|
||||
public class HttpRequestUnitTest {
|
||||
|
||||
@ -48,7 +49,12 @@ public class HttpRequestUnitTest {
|
||||
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
|
||||
}
|
||||
|
||||
@Test
|
||||
/*
|
||||
* This test will fail as soon as the given URL returns a HTTP 2 response.
|
||||
* Therefore, let's leave it commented out.
|
||||
* */
|
||||
@Test
|
||||
@Disabled
|
||||
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
|
@ -1,4 +1,4 @@
|
||||
## Relevant Articles:
|
||||
|
||||
|
||||
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)
|
||||
- [New Features in Java 12](https://www.baeldung.com/java-12-new-features)
|
||||
|
@ -0,0 +1,21 @@
|
||||
package java.com.baeldung.newfeatures;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.NumberFormat;
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CompactNumbersUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNumber_thenCompactValues() {
|
||||
NumberFormat likesShort = NumberFormat.getCompactNumberInstance(new Locale("en", "US"), NumberFormat.Style.SHORT);
|
||||
likesShort.setMaximumFractionDigits(2);
|
||||
assertEquals("2.59K", likesShort.format(2592));
|
||||
NumberFormat likesLong = NumberFormat.getCompactNumberInstance(new Locale("en", "US"), NumberFormat.Style.LONG);
|
||||
likesLong.setMaximumFractionDigits(2);
|
||||
assertEquals("2.59 thousand", likesShort.format(2592));
|
||||
}
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package java.com.baeldung.newfeatures;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class FileMismatchUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIdenticalFiles_thenShouldNotFindMismatch() throws IOException {
|
||||
Path filePath1 = Files.createTempFile("file1", ".txt");
|
||||
Path filePath2 = Files.createTempFile("file2", ".txt");
|
||||
Files.writeString(filePath1, "Java 12 Article");
|
||||
Files.writeString(filePath2, "Java 12 Article");
|
||||
long mismatch = Files.mismatch(filePath1, filePath2);
|
||||
assertEquals(-1, mismatch);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDifferentFiles_thenShouldFindMismatch() throws IOException {
|
||||
Path filePath3 = Files.createTempFile("file3", ".txt");
|
||||
Path filePath4 = Files.createTempFile("file4", ".txt");
|
||||
Files.writeString(filePath3, "Java 12 Article");
|
||||
Files.writeString(filePath4, "Java 12 Tutorial");
|
||||
long mismatch = Files.mismatch(filePath3, filePath4);
|
||||
assertEquals(8, mismatch);
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package java.com.baeldung.newfeatures;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenString_thenRevertValue() {
|
||||
String text = "Baeldung";
|
||||
String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());
|
||||
assertEquals("gnudleaB", transformed);
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package java.com.baeldung.newfeatures;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class TeeingCollectorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSetOfNumbers_thenCalculateAverage() {
|
||||
double mean = Stream.of(1, 2, 3, 4, 5)
|
||||
.collect(Collectors.teeing(Collectors.summingDouble(i -> i), Collectors.counting(), (sum, count) -> sum / count));
|
||||
assertEquals(3.0, mean);
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
### Relevant articles:
|
||||
|
||||
- [Java Switch Statement](https://www.baeldung.com/java-switch)
|
||||
- [New Java 13 Features](https://www.baeldung.com/java-13-new-features)
|
||||
- [New Features in Java 13](https://www.baeldung.com/java-13-new-features)
|
||||
|
@ -10,3 +10,4 @@ This module contains articles about Java 14.
|
||||
- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception)
|
||||
- [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access)
|
||||
- [Java 14 Record Keyword](https://www.baeldung.com/java-record-keyword)
|
||||
- [New Features in Java 14](https://www.baeldung.com/java-14-new-features)
|
||||
|
@ -44,6 +44,8 @@
|
||||
<configuration>
|
||||
<release>${maven.compiler.release}</release>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
<source>14</source>
|
||||
<target>14</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.java14.character;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class IsLetterOrAlphabetUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLetter_thenAssertIsLetterTrue() {
|
||||
assertTrue(Character.isLetter(65));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic(65));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsLetterFalse() {
|
||||
assertFalse(Character.isLetter(837));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic(837));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.baeldung.java14.newfeatues;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MultilineUnitTest {
|
||||
|
||||
@SuppressWarnings("preview")
|
||||
String multiline = """
|
||||
A quick brown fox jumps over a lazy dog; \
|
||||
the lazy dog howls loudly.""";
|
||||
|
||||
@SuppressWarnings("preview")
|
||||
String anotherMultiline = """
|
||||
A quick brown fox jumps over a lazy dog;
|
||||
the lazy dog howls loudly.""";
|
||||
|
||||
@Test
|
||||
public void givenMultilineString_whenSlashUsed_thenNoNewLine() {
|
||||
assertFalse(multiline.contains("\n"));
|
||||
assertTrue(anotherMultiline.contains("\n"));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
package com.baeldung.java14.newfeatues;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RecordUnitTest {
|
||||
|
||||
@SuppressWarnings("preview")
|
||||
public record User(int id, String password) {
|
||||
};
|
||||
|
||||
private User user1 = new User(0, "UserOne");
|
||||
|
||||
@Test
|
||||
public void givenRecord_whenObjInitialized_thenValuesCanBeFetchedWithGetters() {
|
||||
|
||||
assertEquals(0, user1.id());
|
||||
assertEquals("UserOne", user1.password());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRecord_thenEqualsImplemented() {
|
||||
|
||||
User user2 = user1;
|
||||
|
||||
assertEquals(user1, user2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRecord_thenToStringImplemented() {
|
||||
|
||||
assertTrue(user1.toString()
|
||||
.contains("UserOne"));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package com.baeldung.java14.newfeatues;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class SwitchExprUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDay_whenSunday_thenWeekend() {
|
||||
assertTrue(isTodayHolidayInJava8("SUNDAY"));
|
||||
|
||||
assertTrue(isTodayHolidayInJava14("SUNDAY"));
|
||||
|
||||
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> isTodayHolidayInJava8("SOMEDAY"));
|
||||
|
||||
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> isTodayHolidayInJava14("SOMEDAY"));
|
||||
}
|
||||
|
||||
private boolean isTodayHolidayInJava8(String day) {
|
||||
|
||||
boolean isTodayHoliday;
|
||||
switch (day) {
|
||||
case "MONDAY":
|
||||
case "TUESDAY":
|
||||
case "WEDNESDAY":
|
||||
case "THURSDAY":
|
||||
case "FRIDAY":
|
||||
isTodayHoliday = false;
|
||||
break;
|
||||
case "SATURDAY":
|
||||
case "SUNDAY":
|
||||
isTodayHoliday = true;
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("What's a " + day);
|
||||
}
|
||||
return isTodayHoliday;
|
||||
}
|
||||
|
||||
private boolean isTodayHolidayInJava14(String day) {
|
||||
return switch (day) {
|
||||
case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> false;
|
||||
case "SATURDAY", "SUNDAY" -> true;
|
||||
default -> throw new IllegalArgumentException("What's a " + day);
|
||||
};
|
||||
}
|
||||
|
||||
}
|
1
core-java-modules/core-java-15/.mvn/jvm.config
Normal file
1
core-java-modules/core-java-15/.mvn/jvm.config
Normal file
@ -0,0 +1 @@
|
||||
--enable-preview
|
7
core-java-modules/core-java-15/README.md
Normal file
7
core-java-modules/core-java-15/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
## Core Java 15
|
||||
|
||||
This module contains articles about Java 15.
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- [Sealed Classes and Interfaces in Java 15](https://www.baeldung.com/java-sealed-classes-interfaces)
|
76
core-java-modules/core-java-15/pom.xml
Normal file
76
core-java-modules/core-java-15/pom.xml
Normal file
@ -0,0 +1,76 @@
|
||||
<?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>${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>14</source>
|
||||
<target>14</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>
|
||||
<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>
|
@ -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();
|
||||
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.whatsnew.records;
|
||||
|
||||
/**
|
||||
* Java record with a header indicating 2 fields.
|
||||
*/
|
||||
public record Person(String name, int age) {
|
||||
/**
|
||||
* Public constructor that does some basic validation.
|
||||
*/
|
||||
public Person {
|
||||
if (age < 0) {
|
||||
throw new IllegalArgumentException("Age cannot be negative");
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.whatsnew.sealedclasses;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public non-sealed class Employee extends Person {
|
||||
public Date getHiredDate() {
|
||||
return new Date();
|
||||
}
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
package com.baeldung.whatsnew.sealedclasses;
|
||||
|
||||
public final class Manager extends Person {
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.whatsnew.sealedclasses;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public sealed class Person permits Employee, Manager {
|
||||
/**
|
||||
* Demonstration of pattern matching for instanceof
|
||||
*
|
||||
* @param person A Person object
|
||||
* @return
|
||||
*/
|
||||
public static void patternMatchingDemo(Person person) {
|
||||
if(person instanceof Employee employee) {
|
||||
Date hiredDate = employee.getHiredDate();
|
||||
}
|
||||
|
||||
if(person instanceof Employee employee && employee.getHiredDate() != null) {
|
||||
Date hiredDate = employee.getHiredDate();
|
||||
}
|
||||
}
|
||||
}
|
@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -2,8 +2,7 @@ package com.baeldung.java9.modules;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.CoreMatchers.nullValue;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.hamcrest.collection.IsEmptyCollection.empty;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@ -74,7 +73,6 @@ public class ModuleAPIUnitTest {
|
||||
ModuleLayer javaBaseModuleLayer = javaBaseModule.getLayer();
|
||||
|
||||
assertTrue(javaBaseModuleLayer.configuration().findModule(JAVA_BASE_MODULE_NAME).isPresent());
|
||||
assertThat(javaBaseModuleLayer.configuration().modules().size(), is(78));
|
||||
assertTrue(javaBaseModuleLayer.parents().get(0).configuration().parents().isEmpty());
|
||||
}
|
||||
|
||||
@ -108,8 +106,7 @@ public class ModuleAPIUnitTest {
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
assertThat(javaBaseRequires, empty());
|
||||
assertThat(javaSqlRequires.size(), is(3));
|
||||
assertThat(javaSqlRequiresNames, containsInAnyOrder("java.base", "java.xml", "java.logging"));
|
||||
assertThat(javaSqlRequiresNames, hasItems("java.base", "java.xml", "java.logging"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -127,16 +124,13 @@ public class ModuleAPIUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenModules_whenAccessingModuleDescriptorExports_thenExportsAreReturned() {
|
||||
Set<Exports> javaBaseExports = javaBaseModule.getDescriptor().exports();
|
||||
Set<Exports> javaSqlExports = javaSqlModule.getDescriptor().exports();
|
||||
|
||||
Set<String> javaSqlExportsSource = javaSqlExports.stream()
|
||||
.map(Exports::source)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
assertThat(javaBaseExports.size(), is(108));
|
||||
assertThat(javaSqlExports.size(), is(3));
|
||||
assertThat(javaSqlExportsSource, containsInAnyOrder("java.sql", "javax.transaction.xa", "javax.sql"));
|
||||
assertThat(javaSqlExportsSource, hasItems("java.sql", "javax.sql"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -144,7 +138,6 @@ public class ModuleAPIUnitTest {
|
||||
Set<String> javaBaseUses = javaBaseModule.getDescriptor().uses();
|
||||
Set<String> javaSqlUses = javaSqlModule.getDescriptor().uses();
|
||||
|
||||
assertThat(javaBaseUses.size(), is(34));
|
||||
assertThat(javaSqlUses, contains("java.sql.Driver"));
|
||||
}
|
||||
|
||||
|
@ -4,7 +4,7 @@ This module contains articles about core Java features that have been introduced
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Java 9 New Features](https://www.baeldung.com/new-java-9)
|
||||
- [New Features in Java 9](https://www.baeldung.com/new-java-9)
|
||||
- [Java 9 Variable Handles Demystified](http://www.baeldung.com/java-variable-handles)
|
||||
- [Exploring the New HTTP Client in Java 9 and 11](http://www.baeldung.com/java-9-http-client)
|
||||
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar)
|
||||
|
@ -47,12 +47,12 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.11</version>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.7</version>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -7,3 +7,4 @@ This module contains complete guides about arrays in Java
|
||||
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
|
||||
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
|
||||
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
|
||||
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
|
||||
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.genericarrays;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
|
||||
public class MyStack<E> {
|
||||
private E[] elements;
|
||||
private int size = 0;
|
||||
|
||||
public MyStack(Class<E> clazz, int capacity) {
|
||||
elements = (E[]) Array.newInstance(clazz, capacity);
|
||||
}
|
||||
|
||||
public void push(E item) {
|
||||
if (size == elements.length) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
elements[size++] = item;
|
||||
}
|
||||
|
||||
public E pop() {
|
||||
if (size == 0) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
return elements[--size];
|
||||
}
|
||||
|
||||
public E[] getAllElements() {
|
||||
return elements;
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.genericarrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ListToArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenListOfItems_whenToArray_thenReturnArrayOfItems() {
|
||||
List<String> items = new LinkedList<>();
|
||||
items.add("first item");
|
||||
items.add("second item");
|
||||
|
||||
String[] itemsAsArray = items.toArray(new String[0]);
|
||||
|
||||
assertEquals("first item", itemsAsArray[0]);
|
||||
assertEquals("second item", itemsAsArray[1]);
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.baeldung.genericarrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MyStackUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStackWithTwoItems_whenPop_thenReturnLastAdded() {
|
||||
MyStack<String> myStack = new MyStack<>(String.class, 2);
|
||||
myStack.push("hello");
|
||||
myStack.push("example");
|
||||
|
||||
assertEquals("example", myStack.pop());
|
||||
}
|
||||
|
||||
@Test (expected = RuntimeException.class)
|
||||
public void givenStackWithFixedCapacity_whenExceedCapacity_thenThrowException() {
|
||||
MyStack<Integer> myStack = new MyStack<>(Integer.class, 2);
|
||||
myStack.push(100);
|
||||
myStack.push(200);
|
||||
myStack.push(300);
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void givenStack_whenPopOnEmptyStack_thenThrowException() {
|
||||
MyStack<Integer> myStack = new MyStack<>(Integer.class, 1);
|
||||
myStack.push(100);
|
||||
myStack.pop();
|
||||
myStack.pop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStackWithItems_whenGetAllElements_thenSizeShouldEqualTotal() {
|
||||
MyStack<String> myStack = new MyStack<>(String.class, 2);
|
||||
myStack.push("hello");
|
||||
myStack.push("example");
|
||||
|
||||
String[] items = myStack.getAllElements();
|
||||
|
||||
assertEquals(2, items.length);
|
||||
}
|
||||
}
|
@ -29,8 +29,6 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
</properties>
|
||||
</project>
|
@ -68,11 +68,7 @@
|
||||
|
||||
<properties>
|
||||
<shade.plugin.version>3.2.0</shade.plugin.version>
|
||||
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
|
||||
<jmh.version>1.19</jmh.version>
|
||||
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
</properties>
|
||||
</project>
|
@ -76,12 +76,8 @@
|
||||
|
||||
<properties>
|
||||
<shade.plugin.version>3.2.0</shade.plugin.version>
|
||||
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
<guava.version>28.2-jre</guava.version>
|
||||
|
||||
<jmh.version>1.19</jmh.version>
|
||||
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
</properties>
|
||||
</project>
|
6
core-java-modules/core-java-char/README.md
Normal file
6
core-java-modules/core-java-char/README.md
Normal file
@ -0,0 +1,6 @@
|
||||
## Core Java Character
|
||||
|
||||
This module contains articles about Java Character Class
|
||||
|
||||
### Relevant Articles:
|
||||
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)
|
42
core-java-modules/core-java-char/pom.xml
Normal file
42
core-java-modules/core-java-char/pom.xml
Normal file
@ -0,0 +1,42 @@
|
||||
<?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-char</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-char</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>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<openjdk.jmh.version>1.19</openjdk.jmh.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,38 @@
|
||||
package com.baeldung.character;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CharacterGeneralCategoryTypeUnitTest {
|
||||
@Test
|
||||
public void givenACharacter_whenUpperCaseLetter_thenAssertTrue() {
|
||||
assertEquals(Character.UPPERCASE_LETTER, Character.getType('U'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLowerCaseLetter_thenAssertTrue() {
|
||||
assertEquals(Character.LOWERCASE_LETTER, Character.getType('u'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenTitleCaseLetter_thenAssertTrue() {
|
||||
assertEquals(Character.TITLECASE_LETTER, Character.getType('\u01f2'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenModifierLetter_thenAssertTrue() {
|
||||
assertEquals(Character.MODIFIER_LETTER, Character.getType('\u02b0'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenOtherLetter_thenAssertTrue() {
|
||||
assertEquals(Character.OTHER_LETTER, Character.getType('\u05d0'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLetterNumber_thenAssertTrue() {
|
||||
assertEquals(Character.LETTER_NUMBER, Character.getType('\u2164'));
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.character;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class IsLetterOrAlphabetUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenUpperCaseLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic('A'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenTitleCaseLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic('\u01f2'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLowerCaseLetter_thenAssertIsLetterTrue() {
|
||||
assertTrue(Character.isAlphabetic('a'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenModifierLetter_thenAssertIsLetterTrue() {
|
||||
assertTrue(Character.isAlphabetic('\u02b0'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLetter_thenAssertIsLetterTrue() {
|
||||
assertTrue(Character.isLetter('a'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic('a'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsLetterFalse() {
|
||||
assertFalse(Character.isLetter('\u2164'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic('\u2164'));
|
||||
}
|
||||
}
|
@ -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)
|
||||
|
@ -35,7 +35,7 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.10</version>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
7
core-java-modules/core-java-collections-4/README.md
Normal file
7
core-java-modules/core-java-collections-4/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
=========
|
||||
|
||||
## Core Java Collections Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [ArrayList vs. LinkedList vs. HashMap in Java](https://www.baeldung.com/java-arraylist-vs-linkedlist-vs-hashmap)
|
31
core-java-modules/core-java-collections-4/pom.xml
Normal file
31
core-java-modules/core-java-collections-4/pom.xml
Normal file
@ -0,0 +1,31 @@
|
||||
<?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-collections-4</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-4</name>
|
||||
<packaging>jar</packaging>
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.18.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.collections.comparation;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ArrayListUnitTest {
|
||||
|
||||
@Test
|
||||
void givenArrayList_whenItemAddedToSpecificIndex_thenItCanBeRetrieved() {
|
||||
List<String> list = new ArrayList<>();
|
||||
list.add("Daniel");
|
||||
list.add(0, "Marko");
|
||||
assertThat(list).hasSize(2);
|
||||
assertThat(list.get(0)).isEqualTo("Marko");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayList_whenItemRemovedViaIndex_thenListSizeIsReduced() {
|
||||
List<String> list = new ArrayList<>(Arrays.asList("Daniel", "Marko"));
|
||||
list.remove(1);
|
||||
assertThat(list).hasSize(1);
|
||||
assertThat(list).doesNotContain("Marko");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.collections.comparation;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class HashMapUnitTest {
|
||||
|
||||
@Test
|
||||
void givenHashMap_whenItemAddedByKey_thenItCanBeRetrieved() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("123456", "Daniel");
|
||||
map.put("654321", "Marko");
|
||||
assertThat(map.get("654321")).isEqualTo("Marko");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenHashMap_whenItemRemovedByKey_thenMapSizeIsReduced() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("123456", "Daniel");
|
||||
map.put("654321", "Marko");
|
||||
map.remove("654321");
|
||||
assertThat(map).hasSize(1);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.collections.comparation;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class LinkedListUnitTest {
|
||||
|
||||
@Test
|
||||
void givenLinkedList_whenItemIsAppended_thenItCanBeRetrieved() {
|
||||
LinkedList<String> list = new LinkedList<>();
|
||||
list.addLast("Daniel");
|
||||
list.addFirst("Marko");
|
||||
assertThat(list).hasSize(2);
|
||||
assertThat(list.getLast()).isEqualTo("Daniel");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLinkedList_whenItemIsRemoved_thenListSizeIsReduced() {
|
||||
LinkedList<String> list = new LinkedList<>(Arrays.asList("Daniel", "Marko", "David"));
|
||||
list.removeFirst();
|
||||
list.removeLast();
|
||||
assertThat(list).hasSize(1);
|
||||
assertThat(list).containsExactly("Marko");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLinkedList_whenItemInserted_thenItCanBeRetrievedAndDeleted() {
|
||||
LinkedList<String> list = new LinkedList<>();
|
||||
list.push("Daniel");
|
||||
list.push("Marko");
|
||||
assertThat(list.poll()).isEqualTo("Marko");
|
||||
assertThat(list).hasSize(1);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package com.baeldung.collections.comparation;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
class ListVsMapUnitTest {
|
||||
|
||||
@Test
|
||||
void givenList_whenIteratingTroughValues_thenEachValueIsPresent() {
|
||||
List<String> list = new ArrayList<>();
|
||||
list.add("Daniel");
|
||||
list.add("Marko");
|
||||
for (String name : list) {
|
||||
assertThat(name).isIn(list);
|
||||
}
|
||||
assertThat(list).containsExactly("Daniel", "Marko");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenIteratingTroughValues_thenEachValueIsPresent() {
|
||||
Map<Integer, String> map = new HashMap<>();
|
||||
map.put(1, "Daniel");
|
||||
map.put(2, "Marko");
|
||||
for (String name : map.values()) {
|
||||
assertThat(name).isIn(map.values());
|
||||
}
|
||||
assertThat(map.values()).containsExactlyInAnyOrder("Daniel", "Marko");
|
||||
}
|
||||
|
||||
}
|
@ -8,4 +8,4 @@ This module contains articles about the Java ArrayList collection
|
||||
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
|
||||
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
|
||||
- [Removing an Element From an ArrayList](https://www.baeldung.com/java-arraylist-remove-element)
|
||||
|
||||
- [The Capacity of an ArrayList vs the Size of an Array in Java](https://www.baeldung.com/java-list-capacity-array-size)
|
||||
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.listcapacityvsarraysize;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class ArrayCreatorUnitTest {
|
||||
|
||||
@Test
|
||||
void whenSizeOfAnArrayIsNonZero_thenReturnNewArrayOfGivenSize() {
|
||||
Integer[] array = new Integer[10];
|
||||
assertEquals(10, array.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenSizeOfAnArrayIsLessThanZero_thenThrowException() {
|
||||
assertThrows(NegativeArraySizeException.class, () -> { Integer[] array = new Integer[-1]; });
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.listcapacityvsarraysize;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ArrayListCreatorUnitTest {
|
||||
|
||||
@Test
|
||||
void givenValidCapacityOfList_whenCreateListInvoked_thenCreateNewArrayListWithGivenCapacity() {
|
||||
ArrayList<Integer> list = new ArrayList<>(100);
|
||||
|
||||
assertNotNull(list);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInvalidCapacityOfList_whenCreateListInvoked_thenThrowException() {
|
||||
assertThrows(IllegalArgumentException.class, () -> new ArrayList<>(-1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenValidCapacityOfList_whenCreateListInvoked_thenCreateNewArrayListWithSizeZero() {
|
||||
assertEquals(0, new ArrayList<Integer>(100).size());
|
||||
}
|
||||
}
|
@ -36,7 +36,6 @@
|
||||
|
||||
<properties>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
|
@ -26,7 +26,7 @@ public class Product {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public Product addTagsOfOtherProdcut(Product product) {
|
||||
public Product addTagsOfOtherProduct(Product product) {
|
||||
this.tags.addAll(product.getTags());
|
||||
return this;
|
||||
}
|
||||
@ -100,11 +100,11 @@ public class Product {
|
||||
HashMap<String, Product> productsByName = new HashMap<>();
|
||||
Product eBike2 = new Product("E-Bike", "A bike with a battery");
|
||||
eBike2.getTags().add("sport");
|
||||
productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProdcut);
|
||||
productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProduct);
|
||||
|
||||
//Prior to Java 8:
|
||||
if(productsByName.containsKey("E-Bike")) {
|
||||
productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2);
|
||||
productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2);
|
||||
} else {
|
||||
productsByName.put("E-Bike", eBike2);
|
||||
}
|
||||
@ -117,7 +117,7 @@ public class Product {
|
||||
|
||||
productsByName.compute("E-Bike", (k,v) -> {
|
||||
if(v != null) {
|
||||
return v.addTagsOfOtherProdcut(eBike2);
|
||||
return v.addTagsOfOtherProduct(eBike2);
|
||||
} else {
|
||||
return eBike2;
|
||||
}
|
||||
@ -125,7 +125,7 @@ public class Product {
|
||||
|
||||
//Prior to Java 8:
|
||||
if(productsByName.containsKey("E-Bike")) {
|
||||
productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2);
|
||||
productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2);
|
||||
} else {
|
||||
productsByName.put("E-Bike", eBike2);
|
||||
}
|
||||
|
@ -6,4 +6,5 @@ This module contains articles about Map data structures in Java.
|
||||
- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap)
|
||||
- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps)
|
||||
- [The Map.computeIfAbsent() Method](https://www.baeldung.com/java-map-computeifabsent)
|
||||
- [Collections.synchronizedMap vs. ConcurrentHashMap](https://www.baeldung.com/java-synchronizedmap-vs-concurrenthashmap)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)
|
||||
|
@ -15,7 +15,16 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
@ -0,0 +1,96 @@
|
||||
package com.baeldung.map.concurrenthashmap;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
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.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.Setup;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.annotations.Threads;
|
||||
import org.openjdk.jmh.annotations.Warmup;
|
||||
|
||||
@Fork(5)
|
||||
@Threads(10)
|
||||
@Warmup(iterations = 5)
|
||||
@State(Scope.Benchmark)
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public class MapPerformanceComparison {
|
||||
|
||||
private int TEST_NO_ITEMS;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
|
||||
@Setup
|
||||
public void setup() {
|
||||
TEST_NO_ITEMS = 1000;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomReadAndWriteSynchronizedMap() {
|
||||
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
|
||||
performReadAndWriteTest(map);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomReadAndWriteConcurrentHashMap() {
|
||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||
performReadAndWriteTest(map);
|
||||
}
|
||||
|
||||
private void performReadAndWriteTest(final Map<String, Integer> map) {
|
||||
for (int i = 0; i < TEST_NO_ITEMS; i++) {
|
||||
Integer randNumber = (int) Math.ceil(Math.random() * TEST_NO_ITEMS);
|
||||
map.get(String.valueOf(randNumber));
|
||||
map.put(String.valueOf(randNumber), randNumber);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomWriteSynchronizedMap() {
|
||||
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
|
||||
performWriteTest(map);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomWriteConcurrentHashMap() {
|
||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||
performWriteTest(map);
|
||||
}
|
||||
|
||||
private void performWriteTest(final Map<String, Integer> map) {
|
||||
for (int i = 0; i < TEST_NO_ITEMS; i++) {
|
||||
Integer randNumber = (int) Math.ceil(Math.random() * TEST_NO_ITEMS);
|
||||
map.put(String.valueOf(randNumber), randNumber);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomReadSynchronizedMap() {
|
||||
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
|
||||
performReadTest(map);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomReadConcurrentHashMap() {
|
||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||
performReadTest(map);
|
||||
}
|
||||
|
||||
private void performReadTest(final Map<String, Integer> map) {
|
||||
for (int i = 0; i < TEST_NO_ITEMS; i++) {
|
||||
Integer randNumber = (int) Math.ceil(Math.random() * TEST_NO_ITEMS);
|
||||
map.get(String.valueOf(randNumber));
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.map.propertieshashmap;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class PropertiesToHashMapConverter {
|
||||
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
public static HashMap<String, String> typeCastConvert(Properties prop) {
|
||||
Map step1 = prop;
|
||||
Map<String, String> step2 = (Map<String, String>) step1;
|
||||
return new HashMap<>(step2);
|
||||
}
|
||||
|
||||
public static HashMap<String, String> loopConvert(Properties prop) {
|
||||
HashMap<String, String> retMap = new HashMap<>();
|
||||
for (Map.Entry<Object, Object> entry : prop.entrySet()) {
|
||||
retMap.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
|
||||
}
|
||||
return retMap;
|
||||
}
|
||||
|
||||
public static HashMap<String, String> streamConvert(Properties prop) {
|
||||
return prop.entrySet().stream().collect(
|
||||
Collectors.toMap(
|
||||
e -> String.valueOf(e.getKey()),
|
||||
e -> String.valueOf(e.getValue()),
|
||||
(prev, next) -> next, HashMap::new
|
||||
));
|
||||
}
|
||||
|
||||
public static HashMap<String, String> guavaConvert(Properties prop) {
|
||||
return Maps.newHashMap(Maps.fromProperties(prop));
|
||||
}
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package com.baeldung.map.concurrenthashmap;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ConcurrentModificationErrorUnitTest {
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void whenRemoveAndAddOnHashMap_thenConcurrentModificationError() {
|
||||
Map<Integer, String> map = new HashMap<>();
|
||||
map.put(1, "baeldung");
|
||||
map.put(2, "HashMap");
|
||||
Map<Integer, String> synchronizedMap = Collections.synchronizedMap(map);
|
||||
Iterator<Entry<Integer, String>> iterator = synchronizedMap.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
synchronizedMap.put(3, "Modification");
|
||||
iterator.next();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void whenRemoveAndAddOnTreeMap_thenConcurrentModificationError() {
|
||||
Map<Integer, String> map = new TreeMap<>();
|
||||
map.put(1, "baeldung");
|
||||
map.put(2, "HashMap");
|
||||
Map<Integer, String> synchronizedMap = Collections.synchronizedMap(map);
|
||||
Iterator<Entry<Integer, String>> iterator = synchronizedMap.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
synchronizedMap.put(3, "Modification");
|
||||
iterator.next();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void whenRemoveAndAddOnLinkedHashMap_thenConcurrentModificationError() {
|
||||
Map<Integer, String> map = new LinkedHashMap<>();
|
||||
map.put(1, "baeldung");
|
||||
map.put(2, "HashMap");
|
||||
Map<Integer, String> synchronizedMap = Collections.synchronizedMap(map);
|
||||
Iterator<Entry<Integer, String>> iterator = synchronizedMap.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
synchronizedMap.put(3, "Modification");
|
||||
iterator.next();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveAndAddOnConcurrentHashMap_thenNoError() {
|
||||
Map<Integer, String> map = new ConcurrentHashMap<>();
|
||||
map.put(1, "baeldung");
|
||||
map.put(2, "HashMap");
|
||||
Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
map.put(3, "Modification");
|
||||
iterator.next();
|
||||
}
|
||||
|
||||
Assert.assertEquals(3, map.size());
|
||||
}
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
package com.baeldung.map.concurrenthashmap;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NullAllowInMapUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenHashMapBackedSynchronizedMap_whenNullAsKey_thenNoError() {
|
||||
Map<String, Integer> map = Collections
|
||||
.synchronizedMap(new HashMap<String, Integer>());
|
||||
map.put(null, 1);
|
||||
Assert.assertTrue(map.get(null).equals(1));
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenTreeMapBackedSynchronizedMap_whenNullAsKey_thenException() {
|
||||
Map<String, Integer> map = Collections.synchronizedMap(new TreeMap<String, Integer>());
|
||||
map.put(null, 1);
|
||||
Assert.assertTrue(map.get(null).equals(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedHashMapBackedSynchronizedMap_whenNullAsKey_thenNoError() {
|
||||
Map<String, Integer> map = Collections
|
||||
.synchronizedMap(new LinkedHashMap<String, Integer>());
|
||||
map.put(null, 1);
|
||||
Assert.assertTrue(map.get(null).equals(1));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenConcurrentHasMap_whenNullAsKey_thenException() {
|
||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||
map.put(null, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHashMapBackedSynchronizedMap_whenNullAsValue_thenNoError() {
|
||||
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
|
||||
map.put("1", null);
|
||||
Assert.assertNull(map.get("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeMapBackedSynchronizedMap_whenNullAsValue_thenNoError() {
|
||||
Map<String, Integer> map = Collections.synchronizedMap(new TreeMap<String, Integer>());
|
||||
map.put("1", null);
|
||||
Assert.assertNull(map.get("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedHashMapBackedSynchronizedMap_whenNullAsValue_thenNoError() {
|
||||
Map<String, Integer> map = Collections
|
||||
.synchronizedMap(new LinkedHashMap<String, Integer>());
|
||||
map.put("1", null);
|
||||
Assert.assertNull(map.get("1"));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenConcurrentHasMap_whenNullAsValue_thenException() {
|
||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||
map.put("1", null);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.map.hashmap.loadfactor;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class HashMapLoadFactorUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCreateMapWithDefaultParam_thenSucces() {
|
||||
Map<String, String> mapWithDefaultParams = new HashMap<>();
|
||||
mapWithDefaultParams.put("1", "one");
|
||||
mapWithDefaultParams.put("2", "two");
|
||||
mapWithDefaultParams.put("3", "three");
|
||||
mapWithDefaultParams.put("4", "four");
|
||||
mapWithDefaultParams.put("5", "five");
|
||||
|
||||
Assert.assertEquals(5, mapWithDefaultParams.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateMapWithInitialCapacity_thenSucces() {
|
||||
Map<String, String> mapWithInitialCapacity = new HashMap<>(5);
|
||||
mapWithInitialCapacity.put("1", "one");
|
||||
mapWithInitialCapacity.put("2", "two");
|
||||
mapWithInitialCapacity.put("3", "three");
|
||||
|
||||
Assert.assertEquals(3, mapWithInitialCapacity.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateMapWithInitialCapacityAndLF_thenSucces() {
|
||||
Map<String, String> mapWithInitialCapacityAndLF = new HashMap<>(5, 0.5f);
|
||||
mapWithInitialCapacityAndLF.put("1", "one");
|
||||
mapWithInitialCapacityAndLF.put("2", "two");
|
||||
mapWithInitialCapacityAndLF.put("3", "three");
|
||||
mapWithInitialCapacityAndLF.put("4", "four");
|
||||
mapWithInitialCapacityAndLF.put("5", "five");
|
||||
mapWithInitialCapacityAndLF.put("6", "six");
|
||||
mapWithInitialCapacityAndLF.put("7", "seven");
|
||||
mapWithInitialCapacityAndLF.put("8", "eight");
|
||||
mapWithInitialCapacityAndLF.put("9", "nine");
|
||||
mapWithInitialCapacityAndLF.put("10", "ten");
|
||||
|
||||
Assert.assertEquals(10, mapWithInitialCapacityAndLF.size());
|
||||
}
|
||||
}
|
@ -0,0 +1,192 @@
|
||||
package com.baeldung.map.propertieshashmap;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PropertiesToHashMapConverterUnitTest {
|
||||
|
||||
private Properties properties;
|
||||
|
||||
private final static String propertyFileName = "toHashMap.properties";
|
||||
|
||||
@BeforeEach
|
||||
public void setup() throws IOException {
|
||||
properties = new Properties();
|
||||
try (InputStream is = getClass().getClassLoader().getResourceAsStream(propertyFileName)) {
|
||||
if (is != null) {
|
||||
properties.load(is);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void havingPropertiesLoaded_whenCheck_thenEquals() {
|
||||
assertEquals(3, properties.size());
|
||||
assertEquals("str_value", properties.get("property1"));
|
||||
assertEquals("123", properties.get("property2"));
|
||||
assertEquals("", properties.get("property3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPropertiesModified_thenTypeSafeIssues() {
|
||||
compromiseProperties(properties);
|
||||
|
||||
assertEquals(5, properties.size());
|
||||
|
||||
assertNull(properties.getProperty("property4"));
|
||||
assertNotEquals(String.class, properties.get("property4").getClass());
|
||||
assertEquals(456, properties.get("property4"));
|
||||
|
||||
|
||||
assertNull(properties.getProperty("5"));
|
||||
assertNotEquals(String.class, properties.get(5).getClass());
|
||||
assertEquals(10.11, properties.get(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void havingNonModifiedProperties_whenTypeCastConvert_thenNoTypeSafeIssues() {
|
||||
HashMap<String, String> hMap = PropertiesToHashMapConverter.typeCastConvert(properties);
|
||||
|
||||
assertEquals(3, hMap.size());
|
||||
assertEquals(String.class, hMap.get("property1").getClass());
|
||||
assertEquals(properties.get("property1"), hMap.get("property1"));
|
||||
assertEquals(String.class, hMap.get("property2").getClass());
|
||||
assertEquals(properties.get("property2"), hMap.get("property2"));
|
||||
assertEquals(String.class, hMap.get("property3").getClass());
|
||||
assertEquals(properties.get("property3"), hMap.get("property3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void havingModifiedProperties_whenTypeCastConvert_thenClassCastException() {
|
||||
compromiseProperties(properties);
|
||||
HashMap<String, String> hMap = PropertiesToHashMapConverter.typeCastConvert(properties);
|
||||
assertEquals(5, hMap.size());
|
||||
|
||||
assertThrows(ClassCastException.class, () -> {
|
||||
String s = hMap.get("property4");
|
||||
});
|
||||
assertEquals(Integer.class, ((Object) hMap.get("property4")).getClass());
|
||||
|
||||
assertNull(hMap.get("5"));
|
||||
assertNotNull(hMap.get(5));
|
||||
assertThrows(ClassCastException.class, () -> {
|
||||
String s = hMap.get(5);
|
||||
});
|
||||
assertEquals(Double.class, ((Object) hMap.get(5)).getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void havingNonModifiedProperties_whenLoopConvert_thenNoTypeSafeIssues() {
|
||||
HashMap<String, String> hMap = PropertiesToHashMapConverter.loopConvert(properties);
|
||||
|
||||
assertEquals(3, hMap.size());
|
||||
assertEquals(String.class, hMap.get("property1").getClass());
|
||||
assertEquals(properties.get("property1"), hMap.get("property1"));
|
||||
assertEquals(String.class, hMap.get("property2").getClass());
|
||||
assertEquals(properties.get("property2"), hMap.get("property2"));
|
||||
assertEquals(String.class, hMap.get("property3").getClass());
|
||||
assertEquals(properties.get("property3"), hMap.get("property3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void havingModifiedProperties_whenLoopConvert_thenNoClassCastException() {
|
||||
compromiseProperties(properties);
|
||||
HashMap<String, String> hMap = PropertiesToHashMapConverter.loopConvert(properties);
|
||||
assertEquals(5, hMap.size());
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
String s = hMap.get("property4");
|
||||
});
|
||||
assertEquals(String.class, hMap.get("property4").getClass());
|
||||
assertEquals("456", hMap.get("property4"));
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
String s = hMap.get("5");
|
||||
});
|
||||
assertEquals("10.11", hMap.get("5"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void havingNonModifiedProperties_whenStreamConvert_thenNoTypeSafeIssues() {
|
||||
HashMap<String, String> hMap = PropertiesToHashMapConverter.streamConvert(properties);
|
||||
|
||||
assertEquals(3, hMap.size());
|
||||
assertEquals(String.class, hMap.get("property1").getClass());
|
||||
assertEquals(properties.get("property1"), hMap.get("property1"));
|
||||
assertEquals(String.class, hMap.get("property2").getClass());
|
||||
assertEquals(properties.get("property2"), hMap.get("property2"));
|
||||
assertEquals(String.class, hMap.get("property3").getClass());
|
||||
assertEquals(properties.get("property3"), hMap.get("property3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void havingModifiedProperties_whenStreamConvert_thenNoClassCastException() {
|
||||
compromiseProperties(properties);
|
||||
HashMap<String, String> hMap = PropertiesToHashMapConverter.streamConvert(properties);
|
||||
assertEquals(5, hMap.size());
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
String s = hMap.get("property4");
|
||||
});
|
||||
assertEquals(String.class, hMap.get("property4").getClass());
|
||||
assertEquals("456", hMap.get("property4"));
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
String s = hMap.get("5");
|
||||
});
|
||||
assertEquals("10.11", hMap.get("5"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void havingModifiedProperties_whenLoopConvertAndStreamConvert_thenHashMapsSame() {
|
||||
compromiseProperties(properties);
|
||||
HashMap<String, String> hMap1 = PropertiesToHashMapConverter.loopConvert(properties);
|
||||
HashMap<String, String> hMap2 = PropertiesToHashMapConverter.streamConvert(properties);
|
||||
|
||||
assertEquals(hMap2, hMap1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void havingNonModifiedProperties_whenGuavaConvert_thenNoTypeSafeIssues() {
|
||||
HashMap<String, String> hMap = PropertiesToHashMapConverter.guavaConvert(properties);
|
||||
|
||||
assertEquals(3, hMap.size());
|
||||
assertEquals(String.class, hMap.get("property1").getClass());
|
||||
assertEquals(properties.get("property1"), hMap.get("property1"));
|
||||
assertEquals(String.class, hMap.get("property2").getClass());
|
||||
assertEquals(properties.get("property2"), hMap.get("property2"));
|
||||
assertEquals(String.class, hMap.get("property3").getClass());
|
||||
assertEquals(properties.get("property3"), hMap.get("property3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void havingModifiedProperties_whenGuavaConvert_thenUnableToConvertAndThrowException() {
|
||||
compromiseProperties(properties);
|
||||
assertThrows(Exception.class, () -> PropertiesToHashMapConverter.guavaConvert(properties));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void havingModifiedPropertiesWithNoIntegerValue_whenGuavaConvert_thenNullPointerException() {
|
||||
properties.put("property4", 456);
|
||||
assertThrows(NullPointerException.class, () -> PropertiesToHashMapConverter.guavaConvert(properties));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void havingModifiedPropertiesWithNoIntegerKey_whenGuavaConvert_thenClassCastException() {
|
||||
properties.put(5, 10.11);
|
||||
assertThrows(ClassCastException.class, () -> PropertiesToHashMapConverter.guavaConvert(properties));
|
||||
}
|
||||
|
||||
|
||||
private void compromiseProperties(Properties prop) {
|
||||
prop.put("property4", 456);
|
||||
prop.put(5, 10.11);
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
property1=str_value
|
||||
property2=123
|
||||
property3=
|
@ -10,11 +10,17 @@ import org.openjdk.jcstress.annotations.Outcome;
|
||||
import org.openjdk.jcstress.annotations.State;
|
||||
import org.openjdk.jcstress.infra.results.I_Result;
|
||||
|
||||
/**
|
||||
* This is defined as a manual test because it tries to simulate the race conditions
|
||||
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
|
||||
* This will help the CI jobs to ignore these tests and a developer to run them manually.
|
||||
*
|
||||
*/
|
||||
@JCStressTest
|
||||
@Outcome(id = "1", expect = ACCEPTABLE_INTERESTING, desc = "One update lost.")
|
||||
@Outcome(id = "2", expect = ACCEPTABLE, desc = "Both updates.")
|
||||
@State
|
||||
public class MyCounterJCStressUnitTest {
|
||||
public class MyCounterJCStressManualTest {
|
||||
|
||||
private MyCounter counter;
|
||||
|
@ -1,12 +1,17 @@
|
||||
package com.baeldung.concurrent;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import edu.umd.cs.mtc.MultithreadedTestCase;
|
||||
import edu.umd.cs.mtc.TestFramework;
|
||||
|
||||
public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase {
|
||||
/**
|
||||
* This is defined as a manual test because it tries to simulate the race conditions
|
||||
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
|
||||
* This will help the CI jobs to ignore these tests and a developer to run them manually.
|
||||
*
|
||||
*/
|
||||
public class MyCounterMultithreadedTCManualTest extends MultithreadedTestCase {
|
||||
|
||||
private MyCounter counter;
|
||||
|
||||
@ -29,9 +34,8 @@ public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase {
|
||||
assertEquals(2, counter.getCount());
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void testCounter() throws Throwable {
|
||||
TestFramework.runManyTimes(new MyCounterMultithreadedTCUnitTest(), 1000);
|
||||
TestFramework.runManyTimes(new MyCounterMultithreadedTCManualTest(), 1000);
|
||||
}
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
package com.baeldung.concurrent;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* This is defined as a manual test because it tries to simulate the race conditions
|
||||
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
|
||||
* This will help the CI jobs to ignore these tests and a developer to run them manually.
|
||||
*
|
||||
*/
|
||||
public class MyCounterSimpleManualTest {
|
||||
|
||||
@Test
|
||||
public void testCounter() {
|
||||
MyCounter counter = new MyCounter();
|
||||
for (int i = 0; i < 500; i++)
|
||||
counter.increment();
|
||||
assertEquals(500, counter.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCounterWithConcurrency() throws InterruptedException {
|
||||
int numberOfThreads = 100;
|
||||
ExecutorService service = Executors.newFixedThreadPool(10);
|
||||
CountDownLatch latch = new CountDownLatch(numberOfThreads);
|
||||
MyCounter counter = new MyCounter();
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
service.execute(() -> {
|
||||
counter.increment();
|
||||
latch.countDown();
|
||||
});
|
||||
}
|
||||
latch.await();
|
||||
assertEquals(numberOfThreads, counter.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSummationWithConcurrencyAndWait() throws InterruptedException {
|
||||
int numberOfThreads = 2;
|
||||
ExecutorService service = Executors.newFixedThreadPool(10);
|
||||
CountDownLatch latch = new CountDownLatch(numberOfThreads);
|
||||
MyCounter counter = new MyCounter();
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
service.submit(() -> {
|
||||
try {
|
||||
counter.incrementWithWait();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
latch.countDown();
|
||||
});
|
||||
}
|
||||
latch.await();
|
||||
assertEquals(numberOfThreads, counter.getCount());
|
||||
}
|
||||
|
||||
}
|
@ -1,60 +0,0 @@
|
||||
package com.baeldung.concurrent;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class MyCounterSimpleUnitTest {
|
||||
|
||||
@Test
|
||||
public void testCounter() {
|
||||
MyCounter counter = new MyCounter();
|
||||
for (int i = 0; i < 500; i++)
|
||||
counter.increment();
|
||||
assertEquals(500, counter.getCount());
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void testCounterWithConcurrency() throws InterruptedException {
|
||||
int numberOfThreads = 100;
|
||||
ExecutorService service = Executors.newFixedThreadPool(10);
|
||||
CountDownLatch latch = new CountDownLatch(numberOfThreads);
|
||||
MyCounter counter = new MyCounter();
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
service.execute(() -> {
|
||||
counter.increment();
|
||||
latch.countDown();
|
||||
});
|
||||
}
|
||||
latch.await();
|
||||
assertEquals(numberOfThreads, counter.getCount());
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void testSummationWithConcurrencyAndWait() throws InterruptedException {
|
||||
int numberOfThreads = 2;
|
||||
ExecutorService service = Executors.newFixedThreadPool(10);
|
||||
CountDownLatch latch = new CountDownLatch(numberOfThreads);
|
||||
MyCounter counter = new MyCounter();
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
service.submit(() -> {
|
||||
try {
|
||||
counter.incrementWithWait();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
latch.countDown();
|
||||
});
|
||||
}
|
||||
latch.await();
|
||||
assertEquals(numberOfThreads, counter.getCount());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.concurrent;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.code.tempusfugit.concurrency.ConcurrentRule;
|
||||
import com.google.code.tempusfugit.concurrency.RepeatingRule;
|
||||
import com.google.code.tempusfugit.concurrency.annotations.Concurrent;
|
||||
import com.google.code.tempusfugit.concurrency.annotations.Repeating;
|
||||
|
||||
/**
|
||||
* This is defined as a manual test because it tries to simulate the race conditions
|
||||
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
|
||||
* This will help the CI jobs to ignore these tests and a developer to run them manually.
|
||||
*
|
||||
*/
|
||||
public class MyCounterTempusFugitManualTest {
|
||||
|
||||
@Rule
|
||||
public ConcurrentRule concurrently = new ConcurrentRule();
|
||||
@Rule
|
||||
public RepeatingRule rule = new RepeatingRule();
|
||||
|
||||
private static MyCounter counter = new MyCounter();
|
||||
|
||||
@Test
|
||||
@Concurrent(count = 2)
|
||||
@Repeating(repetition = 10)
|
||||
public void runsMultipleTimes() {
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void annotatedTestRunsMultipleTimes() throws InterruptedException {
|
||||
assertEquals(counter.getCount(), 20);
|
||||
}
|
||||
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
package com.baeldung.concurrent;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.code.tempusfugit.concurrency.ConcurrentRule;
|
||||
import com.google.code.tempusfugit.concurrency.RepeatingRule;
|
||||
import com.google.code.tempusfugit.concurrency.annotations.Concurrent;
|
||||
import com.google.code.tempusfugit.concurrency.annotations.Repeating;
|
||||
|
||||
public class MyCounterTempusFugitUnitTest {
|
||||
|
||||
@Rule
|
||||
public ConcurrentRule concurrently = new ConcurrentRule();
|
||||
@Rule
|
||||
public RepeatingRule rule = new RepeatingRule();
|
||||
|
||||
private static MyCounter counter = new MyCounter();
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
@Concurrent(count = 2)
|
||||
@Repeating(repetition = 10)
|
||||
public void runsMultipleTimes() {
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void annotatedTestRunsMultipleTimes() throws InterruptedException {
|
||||
assertEquals(counter.getCount(), 20);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.baeldung.concurrent;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.testing.threadtester.AnnotatedTestRunner;
|
||||
import com.google.testing.threadtester.ThreadedAfter;
|
||||
import com.google.testing.threadtester.ThreadedBefore;
|
||||
import com.google.testing.threadtester.ThreadedMain;
|
||||
import com.google.testing.threadtester.ThreadedSecondary;
|
||||
|
||||
/**
|
||||
* This is defined as a manual test because it tries to simulate the race conditions
|
||||
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
|
||||
* This will help the CI jobs to ignore these tests and a developer to run them manually.
|
||||
*
|
||||
*/
|
||||
public class MyCounterThreadWeaverManualTest {
|
||||
|
||||
private MyCounter counter;
|
||||
|
||||
@ThreadedBefore
|
||||
public void before() {
|
||||
counter = new MyCounter();
|
||||
}
|
||||
|
||||
@ThreadedMain
|
||||
public void mainThread() {
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
@ThreadedSecondary
|
||||
public void secondThread() {
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
@ThreadedAfter
|
||||
public void after() {
|
||||
assertEquals(2, counter.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCounter() {
|
||||
new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class);
|
||||
}
|
||||
|
||||
}
|
@ -1,44 +0,0 @@
|
||||
package com.baeldung.concurrent;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.testing.threadtester.AnnotatedTestRunner;
|
||||
import com.google.testing.threadtester.ThreadedAfter;
|
||||
import com.google.testing.threadtester.ThreadedBefore;
|
||||
import com.google.testing.threadtester.ThreadedMain;
|
||||
import com.google.testing.threadtester.ThreadedSecondary;
|
||||
|
||||
public class MyCounterThreadWeaverUnitTest {
|
||||
|
||||
private MyCounter counter;
|
||||
|
||||
@ThreadedBefore
|
||||
public void before() {
|
||||
counter = new MyCounter();
|
||||
}
|
||||
|
||||
@ThreadedMain
|
||||
public void mainThread() {
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
@ThreadedSecondary
|
||||
public void secondThread() {
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
@ThreadedAfter
|
||||
public void after() {
|
||||
assertEquals(2, counter.getCount());
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void testCounter() {
|
||||
new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class);
|
||||
}
|
||||
|
||||
}
|
@ -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)
|
||||
|
@ -0,0 +1,4 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Binary Semaphore vs Reentrant Lock](https://www.baeldung.com/java-binary-semaphore-vs-reentrant-lock)
|
||||
- [Bad Practices With Synchronization](https://www.baeldung.com/java-synchronization-bad-practices)
|
47
core-java-modules/core-java-concurrency-advanced-4/pom.xml
Normal file
47
core-java-modules/core-java-concurrency-advanced-4/pom.xml
Normal file
@ -0,0 +1,47 @@
|
||||
<?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-concurrency-advanced-4</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-concurrency-advanced-4</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>
|
||||
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-concurrency-advanced-4</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.synchronizationbadpractices;
|
||||
|
||||
public class AnimalBadPractice {
|
||||
|
||||
private String name;
|
||||
private String owner;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
public synchronized void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setOwner(String owner) {
|
||||
synchronized(this) {
|
||||
this.owner = owner;
|
||||
}
|
||||
}
|
||||
|
||||
public AnimalBadPractice() {
|
||||
|
||||
}
|
||||
|
||||
public AnimalBadPractice(String name, String owner) {
|
||||
this.name = name;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.synchronizationbadpractices;
|
||||
|
||||
public class AnimalSolution {
|
||||
|
||||
private final Object objLock1 = new Object();
|
||||
private final Object objLock2 = new Object();
|
||||
|
||||
private String name;
|
||||
private String owner;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
|
||||
public void setName(String name) {
|
||||
synchronized(objLock1) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
public void setOwner(String owner) {
|
||||
synchronized(objLock2) {
|
||||
this.owner = owner;
|
||||
}
|
||||
}
|
||||
|
||||
public AnimalSolution() {
|
||||
|
||||
}
|
||||
|
||||
public AnimalSolution(String name, String owner) {
|
||||
this.name = name;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package com.baeldung.synchronizationbadpractices;
|
||||
|
||||
public class SynchronizationBadPracticeExample {
|
||||
|
||||
public void stringBadPractice1() {
|
||||
String stringLock = "LOCK_STRING";
|
||||
synchronized (stringLock) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
|
||||
private final String stringLock = "LOCK_STRING";
|
||||
public void stringBadPractice2() {
|
||||
synchronized (stringLock) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
|
||||
private final String internedStringLock = new String("LOCK_STRING").intern();
|
||||
public void stringBadPractice3() {
|
||||
synchronized (internedStringLock) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
|
||||
private final Boolean booleanLock = Boolean.FALSE;
|
||||
public void booleanBadPractice() {
|
||||
synchronized (booleanLock) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
|
||||
private int count = 0;
|
||||
private final Integer intLock = count;
|
||||
public void boxedPrimitiveBadPractice() {
|
||||
synchronized (intLock) {
|
||||
count++;
|
||||
// ...
|
||||
}
|
||||
}
|
||||
|
||||
public void classBadPractice() throws InterruptedException {
|
||||
AnimalBadPractice animalObj = new AnimalBadPractice("Tommy", "John");
|
||||
synchronized(animalObj) {
|
||||
while (true) {
|
||||
Thread.sleep(Integer.MAX_VALUE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user