Merge branch 'master' of github.com:eugenp/tutorials

This commit is contained in:
Karsten Silz 2020-06-10 20:34:08 +01:00
commit 879a227f2d
681 changed files with 13331 additions and 1950 deletions

3
aws-app-sync/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [AWS AppSync With Spring Boot](https://www.baeldung.com/aws-appsync-spring)

View File

@ -10,8 +10,8 @@ import java.util.Map;
public class AppSyncClientHelper {
static String apiUrl = "https://m4i3b6icrrb7livfbypfspiifi.appsync-api.us-east-2.amazonaws.com";
static String apiKey = "da2-bm4rpatkkrc5jfyhvvq7itjeke";
static String apiUrl = "<INSERT API URL HERE>";
static String apiKey = "<INSERT API KEY HERE>";
static String API_KEY_HEADER = "x-api-key";
public static WebClient.ResponseSpec getResponseBodySpec(Map<String, Object> requestBody) {

View File

@ -1,5 +1,6 @@
package com.baeldung.awsappsync;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.reactive.function.client.WebClient;
@ -10,6 +11,7 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@Disabled
class AwsAppSyncApplicationTests {
@Test

View File

@ -16,10 +16,6 @@
<relativePath>../../parent-boot-2</relativePath>
</parent>
<properties>
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>

View File

@ -0,0 +1,14 @@
package com.baeldung.determinedatatype
class Person {
private int ageAsInt
private Double ageAsDouble
private String ageAsString
Person() {}
Person(int ageAsInt) { this.ageAsInt = ageAsInt}
Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble}
Person(String ageAsString) { this.ageAsString = ageAsString}
}
class Student extends Person {}

View File

@ -0,0 +1,56 @@
package com.baeldung.determinedatatype
import org.junit.Assert
import org.junit.Test
import com.baeldung.determinedatatype.Person
public class PersonTest {
@Test
public void givenWhenParameterTypeIsInteger_thenReturnTrue() {
Person personObj = new Person(10)
Assert.assertTrue(personObj.ageAsInt instanceof Integer)
}
@Test
public void givenWhenParameterTypeIsDouble_thenReturnTrue() {
Person personObj = new Person(10.0)
Assert.assertTrue((personObj.ageAsDouble).getClass() == Double)
}
@Test
public void givenWhenParameterTypeIsString_thenReturnTrue() {
Person personObj = new Person("10 years")
Assert.assertTrue(personObj.ageAsString.class == String)
}
@Test
public void givenClassName_WhenParameterIsInteger_thenReturnTrue() {
Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class)
}
@Test
public void givenWhenObjectIsInstanceOfType_thenReturnTrue() {
Person personObj = new Person()
Assert.assertTrue(personObj instanceof Person)
}
@Test
public void givenWhenInstanceIsOfSubtype_thenReturnTrue() {
Student studentObj = new Student()
Assert.assertTrue(studentObj in Person)
}
@Test
public void givenGroovyList_WhenFindClassName_thenReturnTrue() {
def ageList = ['ageAsString','ageAsDouble', 10]
Assert.assertTrue(ageList.class == ArrayList)
Assert.assertTrue(ageList.getClass() == ArrayList)
}
@Test
public void givenGrooyMap_WhenFindClassName_thenReturnTrue() {
def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0]
Assert.assertFalse(ageMap.class == LinkedHashMap)
}
}

View File

@ -4,19 +4,19 @@ import java.util.Objects;
public record Person (String name, String address) {
public static String UNKWOWN_ADDRESS = "Unknown";
public static String UNNAMED = "Unnamed";
public static String UNKNOWN_ADDRESS = "Unknown";
public static String UNNAMED = "Unnamed";
public Person {
Objects.requireNonNull(name);
Objects.requireNonNull(address);
}
public Person {
Objects.requireNonNull(name);
Objects.requireNonNull(address);
}
public Person(String name) {
this(name, UNKWOWN_ADDRESS);
}
public Person(String name) {
this(name, UNKNOWN_ADDRESS);
}
public static Person unnamed(String address) {
return new Person(UNNAMED, address);
}
}
public static Person unnamed(String address) {
return new Person(UNNAMED, address);
}
}

View File

@ -134,7 +134,7 @@ public class PersonTest {
Person person = new Person(name);
assertEquals(name, person.name());
assertEquals(Person.UNKWOWN_ADDRESS, person.address());
assertEquals(Person.UNKNOWN_ADDRESS, person.address());
}
@Test
@ -147,4 +147,4 @@ public class PersonTest {
assertEquals(Person.UNNAMED, person.name());
assertEquals(address, person.address());
}
}
}

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-8-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -4,16 +4,15 @@
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-8-datetime</artifactId>
<artifactId>core-java-8-datetime-2</artifactId>
<version>${project.parent.version}</version>
<name>core-java-8-datetime</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>
@ -42,7 +41,6 @@
</dependencies>
<build>
<finalName>core-java-datetime-java8</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>

View File

@ -8,12 +8,11 @@
<version>${project.parent.version}</version>
<name>core-java-8-datetime</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-8</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -9,3 +9,4 @@ This module contains articles about the improvements to core Java features intro
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture)
- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes)

View File

@ -33,6 +33,11 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>

View File

@ -0,0 +1,57 @@
package com.baeldung.java9.io.conversion;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams;
public class InputStreamToByteArrayUnitTest {
@Test
public final void givenUsingPlainJavaOnFixedSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
final byte[] targetArray = new byte[initialStream.available()];
initialStream.read(targetArray);
}
@Test
public final void givenUsingPlainJavaOnUnknownSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
final byte[] data = new byte[1024];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
final byte[] byteArray = buffer.toByteArray();
}
@Test
public void givenUsingPlainJava9_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
byte[] data = is.readAllBytes();
}
@Test
public final void givenUsingGuava_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream initialStream = ByteSource.wrap(new byte[] { 0, 1, 2 })
.openStream();
final byte[] targetArray = ByteStreams.toByteArray(initialStream);
}
@Test
public final void givenUsingCommonsIO_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
final byte[] targetArray = IOUtils.toByteArray(initialStream);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.inputstreamtobytes;
package com.baeldung.java9.io.conversion;
import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams;

View File

@ -12,3 +12,4 @@ This module contains articles about core Java features that have been introduced
- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api)
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
- [Multi-Release JAR Files with Maven](https://www.baeldung.com/maven-multi-release-jars)

View File

@ -28,8 +28,104 @@
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>incubator-features</id>
<build>
<finalName>core-java-9-new-features</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<compilerArgument>--add-modules=jdk.incubator.httpclient</compilerArgument>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--add-modules=jdk.incubator.httpclient</argLine>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>mrjar-generation</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<id>compile-java-8</id>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compileSourceRoots>
<compileSourceRoot>${project.basedir}/src/main/java8</compileSourceRoot>
</compileSourceRoots>
</configuration>
</execution>
<execution>
<id>compile-java-9</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<release>9</release>
<compileSourceRoots>
<compileSourceRoot>${project.basedir}/src/main/java9</compileSourceRoot>
</compileSourceRoots>
<outputDirectory>${project.build.outputDirectory}/META-INF/versions/9</outputDirectory>
</configuration>
</execution>
<execution>
<id>default-testCompile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
<configuration>
<skip>true</skip>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifestEntries>
<Multi-Release>true</Multi-Release>
</manifestEntries>
<manifest>
<mainClass>com.baeldung.multireleaseapp.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<finalName>core-java-9-new-features</finalName>
<plugins>
@ -56,8 +152,10 @@
<!-- testing -->
<assertj.version>3.10.0</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<awaitility.version>4.0.2</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
<maven-jar-plugin.version>3.2.0</maven-jar-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.multireleaseapp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class App {
private static final Logger logger = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
logger.info(String.format("Running on %s", new DefaultVersion().version()));
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.multireleaseapp;
public class DefaultVersion implements Version {
@Override
public String version() {
return System.getProperty("java.version");
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.multireleaseapp;
interface Version {
public String version();
}

View File

@ -0,0 +1,9 @@
package com.baeldung.multireleaseapp;
public class DefaultVersion implements Version {
@Override
public String version() {
return Runtime.version().toString();
}
}

View File

@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat;
/**
* Created by adam.
*/
public class HttpClientTest {
public class HttpClientIntegrationTest {
@Test
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
@ -55,7 +55,7 @@ public class HttpClientTest {
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
assertThat(response.body(), containsString("https://stackoverflow.com/"));
assertThat(response.body(), containsString(""));
}
@Test

View File

@ -22,7 +22,7 @@ import static org.junit.Assert.assertThat;
/**
* Created by adam.
*/
public class HttpRequestTest {
public class HttpRequestIntegrationTest {
@Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {

View File

@ -18,7 +18,7 @@ import static org.junit.Assert.assertThat;
/**
* Created by adam.
*/
public class HttpResponseTest {
public class HttpResponseIntegrationTest {
@Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {

View File

@ -5,10 +5,12 @@ import org.junit.Test;
import java.util.List;
import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
public class ReactiveStreamsTest {
public class ReactiveStreamsUnitTest {
@Test
public void givenPublisher_whenSubscribeToIt_thenShouldConsumeAllElements() throws InterruptedException {
@ -25,7 +27,7 @@ public class ReactiveStreamsTest {
//then
await().atMost(1000, TimeUnit.MILLISECONDS).until(
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(items)
);
}
@ -46,7 +48,7 @@ public class ReactiveStreamsTest {
publisher.close();
//then
await().atMost(1000, TimeUnit.MILLISECONDS).until(
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expectedResult)
);
}
@ -66,7 +68,7 @@ public class ReactiveStreamsTest {
publisher.close();
//then
await().atMost(1000, TimeUnit.MILLISECONDS).until(
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expected)
);
}

View File

@ -1,106 +0,0 @@
package com.baeldung.java9.varhandles;
import org.junit.Test;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import static org.assertj.core.api.Assertions.assertThat;
public class VariableHandlesTest {
public int publicTestVariable = 1;
private int privateTestVariable = 1;
public int variableToSet = 1;
public int variableToCompareAndSet = 1;
public int variableToGetAndAdd = 0;
public byte variableToBitwiseOr = 0;
@Test
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
assertThat(publicIntHandle.coordinateTypes().size() == 1);
assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandles.class);
}
@Test
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
VarHandle privateIntHandle = MethodHandles
.privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup())
.findVarHandle(VariableHandlesTest.class, "privateTestVariable", int.class);
assertThat(privateIntHandle.coordinateTypes().size() == 1);
assertThat(privateIntHandle.coordinateTypes().get(0) == VariableHandlesTest.class);
}
@Test
public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
VarHandle arrayVarHandle = MethodHandles
.arrayElementVarHandle(int[].class);
assertThat(arrayVarHandle.coordinateTypes().size() == 2);
assertThat(arrayVarHandle.coordinateTypes().get(0) == int[].class);
}
@Test
public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
assertThat((int) publicIntHandle.get(this) == 1);
}
@Test
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "variableToSet", int.class);
publicIntHandle.set(this, 15);
assertThat((int) publicIntHandle.get(this) == 15);
}
@Test
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "variableToCompareAndSet", int.class);
publicIntHandle.compareAndSet(this, 1, 100);
assertThat((int) publicIntHandle.get(this) == 100);
}
@Test
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "variableToGetAndAdd", int.class);
int before = (int) publicIntHandle.getAndAdd(this, 200);
assertThat(before == 0);
assertThat((int) publicIntHandle.get(this) == 200);
}
@Test
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "variableToBitwiseOr", byte.class);
byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127);
assertThat(before == 0);
assertThat(variableToBitwiseOr == 127);
}
}

View File

@ -0,0 +1,105 @@
package com.baeldung.java9.varhandles;
import org.junit.Test;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import static org.junit.Assert.assertEquals;
public class VariableHandlesUnitTest {
public int publicTestVariable = 1;
private int privateTestVariable = 1;
public int variableToSet = 1;
public int variableToCompareAndSet = 1;
public int variableToGetAndAdd = 0;
public byte variableToBitwiseOr = 0;
@Test
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
VarHandle PUBLIC_TEST_VARIABLE = MethodHandles
.lookup()
.in(VariableHandlesUnitTest.class)
.findVarHandle(VariableHandlesUnitTest.class, "publicTestVariable", int.class);
assertEquals(1, PUBLIC_TEST_VARIABLE.coordinateTypes().size());
assertEquals(VariableHandlesUnitTest.class, PUBLIC_TEST_VARIABLE.coordinateTypes().get(0));
}
@Test
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
VarHandle PRIVATE_TEST_VARIABLE = MethodHandles
.privateLookupIn(VariableHandlesUnitTest.class, MethodHandles.lookup())
.findVarHandle(VariableHandlesUnitTest.class, "privateTestVariable", int.class);
assertEquals(1, PRIVATE_TEST_VARIABLE.coordinateTypes().size());
assertEquals(VariableHandlesUnitTest.class, PRIVATE_TEST_VARIABLE.coordinateTypes().get(0));
}
@Test
public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
VarHandle arrayVarHandle = MethodHandles
.arrayElementVarHandle(int[].class);
assertEquals(2, arrayVarHandle.coordinateTypes().size());
assertEquals(int[].class, arrayVarHandle.coordinateTypes().get(0));
}
@Test
public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException {
VarHandle PUBLIC_TEST_VARIABLE = MethodHandles
.lookup()
.in(VariableHandlesUnitTest.class)
.findVarHandle(VariableHandlesUnitTest.class, "publicTestVariable", int.class);
assertEquals(1, (int) PUBLIC_TEST_VARIABLE.get(this));
}
@Test
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle VARIABLE_TO_SET = MethodHandles
.lookup()
.in(VariableHandlesUnitTest.class)
.findVarHandle(VariableHandlesUnitTest.class, "variableToSet", int.class);
VARIABLE_TO_SET.set(this, 15);
assertEquals(15, (int) VARIABLE_TO_SET.get(this));
}
@Test
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle VARIABLE_TO_COMPARE_AND_SET = MethodHandles
.lookup()
.in(VariableHandlesUnitTest.class)
.findVarHandle(VariableHandlesUnitTest.class, "variableToCompareAndSet", int.class);
VARIABLE_TO_COMPARE_AND_SET.compareAndSet(this, 1, 100);
assertEquals(100, (int) VARIABLE_TO_COMPARE_AND_SET.get(this));
}
@Test
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle VARIABLE_TO_GET_AND_ADD = MethodHandles
.lookup()
.in(VariableHandlesUnitTest.class)
.findVarHandle(VariableHandlesUnitTest.class, "variableToGetAndAdd", int.class);
int before = (int) VARIABLE_TO_GET_AND_ADD.getAndAdd(this, 200);
assertEquals(0, before);
assertEquals(200, (int) VARIABLE_TO_GET_AND_ADD.get(this));
}
@Test
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle VARIABLE_TO_BITWISE_OR = MethodHandles
.lookup()
.in(VariableHandlesUnitTest.class)
.findVarHandle(VariableHandlesUnitTest.class, "variableToBitwiseOr", byte.class);
byte before = (byte) VARIABLE_TO_BITWISE_OR.getAndBitwiseOr(this, (byte) 127);
assertEquals(0, before);
assertEquals(127, (byte) VARIABLE_TO_BITWISE_OR.get(this));
}
}

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-9-streams</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<build>

View File

@ -10,10 +10,10 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<build>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>1.0.0-SNAPSHOT</version>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>1.0.0-SNAPSHOT</version>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>1.0.0-SNAPSHOT</version>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>1.0.0-SNAPSHOT</version>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>1.0.0-SNAPSHOT</version>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,8 +5,8 @@
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -7,12 +7,11 @@
<artifactId>core-java-collections-2</artifactId>
<name>core-java-collections-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -9,3 +9,4 @@
- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall)
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Fail-Safe Iterator vs Fail-Fast Iterator](https://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-array-list</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-list-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-list-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-list</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -7,12 +7,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-maps-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -7,12 +7,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-maps-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -6,12 +6,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-maps</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-set</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-advanced-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -12,4 +12,5 @@ This module contains articles about advanced topics about multithreading with co
- [Asynchronous Programming in Java](https://www.baeldung.com/java-asynchronous-programming)
- [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)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@ -9,12 +9,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-advanced-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -0,0 +1,66 @@
package com.baeldung.abaproblem;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class Account {
private AtomicInteger balance;
private AtomicInteger transactionCount;
private ThreadLocal<Integer> currentThreadCASFailureCount;
public Account() {
this.balance = new AtomicInteger(0);
this.transactionCount = new AtomicInteger(0);
this.currentThreadCASFailureCount = new ThreadLocal<>();
this.currentThreadCASFailureCount.set(0);
}
public int getBalance() {
return balance.get();
}
public int getTransactionCount() {
return transactionCount.get();
}
public int getCurrentThreadCASFailureCount() {
return currentThreadCASFailureCount.get();
}
public boolean withdraw(int amount) {
int current = getBalance();
maybeWait();
boolean result = balance.compareAndSet(current, current - amount);
if (result) {
transactionCount.incrementAndGet();
} else {
int currentCASFailureCount = currentThreadCASFailureCount.get();
currentThreadCASFailureCount.set(currentCASFailureCount + 1);
}
return result;
}
private void maybeWait() {
if ("thread1".equals(Thread.currentThread().getName())) {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public boolean deposit(int amount) {
int current = balance.get();
boolean result = balance.compareAndSet(current, current + amount);
if (result) {
transactionCount.incrementAndGet();
} else {
int currentCASFailureCount = currentThreadCASFailureCount.get();
currentThreadCASFailureCount.set(currentCASFailureCount + 1);
}
return result;
}
}

View File

@ -9,13 +9,11 @@ public class StampedAccount {
private AtomicStampedReference<Integer> account = new AtomicStampedReference<>(0, 0);
public int getBalance() {
return this.account.get(new int[1]);
return account.getReference();
}
public int getStamp() {
int[] stamps = new int[1];
this.account.get(stamps);
return stamps[0];
return account.getStamp();
}
public boolean deposit(int funds) {

View File

@ -0,0 +1,98 @@
package com.baeldung.abaproblem;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class AccountUnitTest {
private Account account;
@BeforeEach
public void setUp() {
account = new Account();
}
@Test
public void zeroBalanceInitializationTest() {
assertEquals(0, account.getBalance());
assertEquals(0, account.getTransactionCount());
assertEquals(0, account.getCurrentThreadCASFailureCount());
}
@Test
public void depositTest() {
final int moneyToDeposit = 50;
assertTrue(account.deposit(moneyToDeposit));
assertEquals(moneyToDeposit, account.getBalance());
}
@Test
public void withdrawTest() throws InterruptedException {
final int defaultBalance = 50;
final int moneyToWithdraw = 20;
account.deposit(defaultBalance);
assertTrue(account.withdraw(moneyToWithdraw));
assertEquals(defaultBalance - moneyToWithdraw, account.getBalance());
}
@Test
public void abaProblemTest() throws InterruptedException {
final int defaultBalance = 50;
final int amountToWithdrawByThread1 = 20;
final int amountToWithdrawByThread2 = 10;
final int amountToDepositByThread2 = 10;
assertEquals(0, account.getTransactionCount());
assertEquals(0, account.getCurrentThreadCASFailureCount());
account.deposit(defaultBalance);
assertEquals(1, account.getTransactionCount());
Thread thread1 = new Thread(() -> {
// this will take longer due to the name of the thread
assertTrue(account.withdraw(amountToWithdrawByThread1));
// thread 1 fails to capture ABA problem
assertNotEquals(1, account.getCurrentThreadCASFailureCount());
}, "thread1");
Thread thread2 = new Thread(() -> {
assertTrue(account.deposit(amountToDepositByThread2));
assertEquals(defaultBalance + amountToDepositByThread2, account.getBalance());
// this will be fast due to the name of the thread
assertTrue(account.withdraw(amountToWithdrawByThread2));
// thread 1 didn't finish yet, so the original value will be in place for it
assertEquals(defaultBalance, account.getBalance());
assertEquals(0, account.getCurrentThreadCASFailureCount());
}, "thread2");
thread1.start();
thread2.start();
thread1.join();
thread2.join();
// compareAndSet operation succeeds for thread 1
assertEquals(defaultBalance - amountToWithdrawByThread1, account.getBalance());
//but there are other transactions
assertNotEquals(2, account.getTransactionCount());
// thread 2 did two modifications as well
assertEquals(4, account.getTransactionCount());
}
}

View File

@ -40,15 +40,15 @@ public class ExchangerPipeLineManualTest {
Runnable processor = () -> {
Queue<String> processorBuffer = new ConcurrentLinkedQueue<>();
Queue<String> writterBuffer = new ConcurrentLinkedQueue<>();
Queue<String> writerBuffer = new ConcurrentLinkedQueue<>();
try {
processorBuffer = readerExchanger.exchange(processorBuffer);
while (true) {
writterBuffer.add(processorBuffer.poll());
writerBuffer.add(processorBuffer.poll());
if (processorBuffer.isEmpty()) {
try {
processorBuffer = readerExchanger.exchange(processorBuffer);
writterBuffer = writerExchanger.exchange(writterBuffer);
writerBuffer = writerExchanger.exchange(writerBuffer);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
@ -62,13 +62,13 @@ public class ExchangerPipeLineManualTest {
};
Runnable writer = () -> {
Queue<String> writterBuffer = new ConcurrentLinkedQueue<>();
Queue<String> writerBuffer = new ConcurrentLinkedQueue<>();
try {
writterBuffer = writerExchanger.exchange(writterBuffer);
writerBuffer = writerExchanger.exchange(writerBuffer);
while (true) {
System.out.println(writterBuffer.poll());
if (writterBuffer.isEmpty()) {
writterBuffer = writerExchanger.exchange(writterBuffer);
System.out.println(writerBuffer.poll());
if (writerBuffer.isEmpty()) {
writerBuffer = writerExchanger.exchange(writerBuffer);
}
}
} catch (InterruptedException e) {

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-advanced</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-basic-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<build>

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-basic</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -23,7 +23,12 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
@ -42,6 +47,8 @@
<properties>
<jmh.version>1.21</jmh.version>
<guava.version>28.2-jre</guava.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,66 @@
package com.baeldung.concurrent.queue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.FixMethodOrder;
import org.junit.Test;
@FixMethodOrder
public class TestConcurrentLinkedQueue {
@Test
public void givenThereIsExistingCollection_WhenAddedIntoQueue_ThenShouldContainElements() {
Collection<Integer> elements = Arrays.asList(1, 2, 3, 4, 5);
ConcurrentLinkedQueue<Integer> concurrentLinkedQueue = new ConcurrentLinkedQueue<>(elements);
assertThat(concurrentLinkedQueue).containsExactly(1, 2, 3, 4, 5);
}
@Test
public void givenQueueIsEmpty_WhenAccessingTheQueue_ThenQueueReturnsNull() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
ConcurrentLinkedQueue<Integer> concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
executorService.submit(() -> assertNull("Retrieve object is null", concurrentLinkedQueue.poll()));
TimeUnit.SECONDS.sleep(1);
executorService.awaitTermination(1, TimeUnit.SECONDS);
executorService.shutdown();
}
@Test
public void givenProducerOffersElementInQueue_WhenConsumerPollsQueue_ThenItRetrievesElement() throws Exception {
int element = 1;
ExecutorService executorService = Executors.newFixedThreadPool(2);
ConcurrentLinkedQueue<Integer> concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
Runnable offerTask = () -> concurrentLinkedQueue.offer(element);
Callable<Integer> pollTask = () -> {
while (concurrentLinkedQueue.peek() != null) {
return concurrentLinkedQueue.poll()
.intValue();
}
return null;
};
executorService.submit(offerTask);
TimeUnit.SECONDS.sleep(1);
Future<Integer> returnedElement = executorService.submit(pollTask);
assertThat(returnedElement.get()
.intValue(), is(equalTo(element)));
executorService.awaitTermination(1, TimeUnit.SECONDS);
executorService.shutdown();
}
}

View File

@ -0,0 +1,81 @@
package com.baeldung.concurrent.queue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.junit.FixMethodOrder;
import org.junit.Test;
@FixMethodOrder
public class TestLinkedBlockingQueue {
@Test
public void givenThereIsExistingCollection_WhenAddedIntoQueue_ThenShouldContainElements() {
Collection<Integer> elements = Arrays.asList(1, 2, 3, 4, 5);
LinkedBlockingQueue<Integer> linkedBlockingQueue = new LinkedBlockingQueue<>(elements);
assertThat(linkedBlockingQueue).containsExactly(1, 2, 3, 4, 5);
}
@Test
public void givenQueueIsEmpty_WhenAccessingTheQueue_ThenThreadBlocks() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
LinkedBlockingQueue<Integer> linkedBlockingQueue = new LinkedBlockingQueue<>();
executorService.submit(() -> {
try {
linkedBlockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
TimeUnit.SECONDS.sleep(1);
executorService.awaitTermination(1, TimeUnit.SECONDS);
executorService.shutdown();
}
@Test
public void givenProducerPutsElementInQueue_WhenConsumerAccessQueue_ThenItRetrieve() {
int element = 10;
ExecutorService executorService = Executors.newFixedThreadPool(2);
LinkedBlockingQueue<Integer> linkedBlockingQueue = new LinkedBlockingQueue<>();
Runnable putTask = () -> {
try {
linkedBlockingQueue.put(element);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Callable<Integer> takeTask = () -> {
try {
return linkedBlockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
};
executorService.submit(putTask);
Future<Integer> returnElement = executorService.submit(takeTask);
try {
TimeUnit.SECONDS.sleep(1);
assertThat(returnElement.get()
.intValue(), is(equalTo(element)));
executorService.awaitTermination(1, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
executorService.shutdown();
}
}

View File

@ -8,12 +8,11 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-collections</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -0,0 +1,5 @@
#Core Java Console
[Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output)
[Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf)
[ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)

View File

@ -0,0 +1,142 @@
<?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-console</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-console</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>
<build>
<finalName>core-java-console</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<configuration>
<executable>java</executable>
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>${source.version}</source>
<target>${target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<include>**/*IntTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
</properties>
</project>

View File

@ -1,10 +1,9 @@
package com.baeldung.asciiart;
import java.awt.Font;
import com.baeldung.asciiart.AsciiArt.Settings;
import org.junit.Test;
import com.baeldung.asciiart.AsciiArt.Settings;
import java.awt.*;
public class AsciiArtIntegrationTest {
@ -16,5 +15,4 @@ public class AsciiArtIntegrationTest {
asciiArt.drawString(text, "*", settings);
}
}

View File

@ -8,12 +8,11 @@
<version>${project.parent.version}</version>
<name>core-java-date-operations-1</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,4 +8,5 @@ This module contains articles about date operations in Java.
- [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime)
- [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone)
- [How to determine day of week by passing specific date in Java?](https://www.baeldung.com/java-get-day-of-week)
- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year)
- [[<-- Prev]](/core-java-modules/core-java-date-operations-1)

View File

@ -8,12 +8,11 @@
<version>${project.parent.version}</version>
<name>core-java-date-operations-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,12 +8,11 @@
<version>${project.parent.version}</version>
<name>core-java-datetime-conversion</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -8,12 +8,11 @@
<version>${project.parent.version}</version>
<name>core-java-datetime-string</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -9,3 +9,6 @@ This module contains articles about core java exceptions
- [java.net.UnknownHostException: Invalid Hostname for Server](https://www.baeldung.com/java-unknownhostexception)
- [How to Handle Java SocketException](https://www.baeldung.com/java-socketexception)
- [Java Suppressed Exceptions](https://www.baeldung.com/java-suppressed-exceptions)
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler)
- [How to Find an Exceptions Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)

View File

@ -7,12 +7,11 @@
<artifactId>core-java-exceptions-2</artifactId>
<name>core-java-exceptions-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>
@ -23,6 +22,11 @@
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency>
</dependencies>
<description> </description>
@ -30,6 +34,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<commons.lang3.version>3.10</commons.lang3.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import java.io.BufferedReader;
import java.io.File;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import java.util.ArrayList;
import java.util.Iterator;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import java.net.MalformedURLException;
import java.net.URL;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import java.text.DateFormat;
import java.text.ParseException;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.rootcausefinder;
package com.baeldung.rootcausefinder;
import java.time.LocalDate;
import java.time.Period;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.junit.After;
import org.junit.Before;

View File

@ -1,7 +1,7 @@
package com.baeldung.exceptions.rootcausefinder;
package com.baeldung.rootcausefinder;
import com.baeldung.exceptions.rootcausefinder.RootCauseFinder.CalculationException;
import com.baeldung.exceptions.rootcausefinder.RootCauseFinder.DateOutOfRangeException;
import com.baeldung.rootcausefinder.RootCauseFinder.CalculationException;
import com.baeldung.rootcausefinder.RootCauseFinder.DateOutOfRangeException;
import com.google.common.base.Throwables;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.junit.jupiter.api.Assertions;
@ -11,8 +11,7 @@ import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import static com.baeldung.exceptions.rootcausefinder.RootCauseFinder.AgeCalculator;
import static com.baeldung.exceptions.rootcausefinder.RootCauseFinder.findCauseUsingPlainJava;
import static com.baeldung.rootcausefinder.RootCauseFinder.AgeCalculator;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@ -38,7 +37,7 @@ public class RootCauseFinderUnitTest {
try {
AgeCalculator.calculateAge("010102");
} catch (CalculationException ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof DateTimeParseException);
assertTrue(RootCauseFinder.findCauseUsingPlainJava(ex) instanceof DateTimeParseException);
}
}
@ -47,7 +46,7 @@ public class RootCauseFinderUnitTest {
try {
AgeCalculator.calculateAge("2020-04-04");
} catch (CalculationException ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof DateOutOfRangeException);
assertTrue(RootCauseFinder.findCauseUsingPlainJava(ex) instanceof DateOutOfRangeException);
}
}
@ -56,7 +55,7 @@ public class RootCauseFinderUnitTest {
try {
AgeCalculator.calculateAge(null);
} catch (Exception ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof IllegalArgumentException);
assertTrue(RootCauseFinder.findCauseUsingPlainJava(ex) instanceof IllegalArgumentException);
}
}

View File

@ -12,9 +12,5 @@ This module contains articles about core java exceptions
- [“Sneaky Throws” in Java](https://www.baeldung.com/java-sneaky-throws)
- [The StackOverflowError in Java](https://www.baeldung.com/java-stack-overflow-error)
- [Checked and Unchecked Exceptions in Java](https://www.baeldung.com/java-checked-unchecked-exceptions)
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler)
- [Common Java Exceptions](https://www.baeldung.com/java-common-exceptions)
- [How to Find an Exceptions Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
- [Is It a Bad Practice to Catch Throwable?](https://www.baeldung.com/java-catch-throwable-bad-practice)
- [[Next -->]](/core-java-modules/core-java-exceptions-2)

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