Merge pull request #2 from eugenp/master

Updating local repo
This commit is contained in:
Umang Budhwar
2020-07-10 20:31:57 +05:30
committed by GitHub
2898 changed files with 18558 additions and 479878 deletions
+1
View File
@@ -9,3 +9,4 @@ This module contains articles about Java 14.
- [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof)
- [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)
@@ -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);
}
}
@@ -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());
}
}
}
@@ -4,9 +4,9 @@
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>
<name>core-java-8-datetime-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
@@ -41,7 +41,6 @@
</dependencies>
<build>
<finalName>core-java-datetime-java8</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
@@ -5,7 +5,7 @@ This module contains articles about the improvements to core Java features intro
### Relevant Articles:
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
- [Java Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
- [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)
@@ -64,7 +64,7 @@
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
<url>https://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
@@ -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)
@@ -16,6 +16,11 @@
</parent>
<dependencies>
<dependency>
<groupId>io.reactivex.rxjava3</groupId>
<artifactId>rxjava</artifactId>
<version>${rxjava.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@@ -28,8 +33,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>
@@ -48,16 +149,19 @@
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
<url>https://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<properties>
<rxjava.version>3.0.0</rxjava.version>
<!-- 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>
@@ -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()));
}
}
@@ -0,0 +1,9 @@
package com.baeldung.multireleaseapp;
public class DefaultVersion implements Version {
@Override
public String version() {
return System.getProperty("java.version");
}
}
@@ -0,0 +1,5 @@
package com.baeldung.multireleaseapp;
interface Version {
public String version();
}
@@ -0,0 +1,9 @@
package com.baeldung.multireleaseapp;
public class DefaultVersion implements Version {
@Override
public String version() {
return Runtime.version().toString();
}
}
@@ -0,0 +1,23 @@
package com.baeldung.java9.currentmethod;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CurrentExecutingMethodUnitTest {
@Test
public void givenJava9_whenWalkingTheStack_thenFindMethod() {
StackWalker walker = StackWalker.getInstance();
Optional<String> methodName = walker.walk(frames -> frames
.findFirst()
.map(StackWalker.StackFrame::getMethodName)
);
assertTrue(methodName.isPresent());
assertEquals("givenJava9_whenWalkingTheStack_thenFindMethod", methodName.get());
}
}
@@ -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
@@ -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 {
@@ -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 {
@@ -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)
);
}
@@ -0,0 +1,71 @@
package com.baeldung.java9.streams.reactive.flowvsrx;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class FlowApiLiveVideo {
static class VideoPlayer implements Flow.Subscriber<VideoFrame> {
Flow.Subscription subscription = null;
private long consumerDelay = 30;
public VideoPlayer(long consumerDelay) {
this.consumerDelay = consumerDelay;
}
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
subscription.request(1);
}
@Override
public void onNext(VideoFrame item) {
try {
Thread.sleep(consumerDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
}
static class VideoStreamServer extends SubmissionPublisher<VideoFrame> {
ScheduledExecutorService executor = null;
public VideoStreamServer(int bufferSize) {
super(Executors.newSingleThreadExecutor(), bufferSize);
executor = Executors.newScheduledThreadPool(1);
}
void startStreaming(long produceDelay, Runnable onDrop) {
AtomicLong frameNumber = new AtomicLong();
executor.scheduleWithFixedDelay(() -> {
offer(new VideoFrame(frameNumber.getAndIncrement()), (subscriber, videoFrame) -> {
subscriber.onError(new RuntimeException("Frame#" + videoFrame.getNumber() + " dropped because of back pressure"));
onDrop.run();
return true;
});
}, 0, produceDelay, TimeUnit.MILLISECONDS);
}
}
public static void streamLiveVideo(long produceDelay, long consumeDelay, int bufferSize, Runnable onError){
FlowApiLiveVideo.VideoStreamServer streamServer = new FlowApiLiveVideo.VideoStreamServer(bufferSize);
streamServer.subscribe(new FlowApiLiveVideo.VideoPlayer(consumeDelay));
streamServer.startStreaming(produceDelay, onError);
}
}
@@ -0,0 +1,61 @@
package com.baeldung.java9.streams.reactive.flowvsrx;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import static org.awaitility.Awaitility.await;
public class LiveVideoFlowVsRxUnitTest {
private final static long SLOW_CONSUMER_DELAY = 30;
private final static long FAST_CONSUMER_DELAY = 1;
private final static long PRODUCER_DELAY = 1;
private final static int BUFFER_SIZE = 10;
private final static long AWAIT = 1000;
@Test
public void givenSlowVideoPlayer_whenSubscribedToFlowApiLiveVideo_thenExpectErrorOnBackPressure() {
AtomicLong errors = new AtomicLong();
FlowApiLiveVideo.streamLiveVideo(PRODUCER_DELAY, SLOW_CONSUMER_DELAY, BUFFER_SIZE, errors::incrementAndGet);
await()
.atMost(AWAIT, TimeUnit.MILLISECONDS)
.untilAsserted(() -> Assertions.assertTrue(errors.get() > 0));
}
@Test
public void givenFastVideoPlayer_whenSubscribedToFlowApiLiveVideo_thenExpectNoErrorOnBackPressure() throws InterruptedException {
AtomicLong errors = new AtomicLong();
FlowApiLiveVideo.streamLiveVideo(PRODUCER_DELAY, FAST_CONSUMER_DELAY, BUFFER_SIZE, errors::incrementAndGet);
Thread.sleep(AWAIT);
Assertions.assertEquals(0, errors.get());
}
@Test
public void givenSlowVideoPlayer_whenSubscribedToRxJavaLiveVideo_thenExpectErrorOnBackPressure() {
AtomicLong errors = new AtomicLong();
RxJavaLiveVideo.streamLiveVideo(PRODUCER_DELAY, SLOW_CONSUMER_DELAY, BUFFER_SIZE, errors::incrementAndGet);
await()
.atMost(AWAIT, TimeUnit.MILLISECONDS)
.untilAsserted(() -> Assertions.assertTrue(errors.get() > 0));
}
@Test
public void givenFastVideoPlayer_whenSubscribedToRxJavaLiveVideo_thenExpectNoErrorOnBackPressure() throws InterruptedException {
AtomicLong errors = new AtomicLong();
RxJavaLiveVideo.streamLiveVideo(PRODUCER_DELAY, FAST_CONSUMER_DELAY, BUFFER_SIZE, errors::incrementAndGet);
Thread.sleep(AWAIT);
Assertions.assertEquals(0, errors.get());
}
}
@@ -0,0 +1,36 @@
package com.baeldung.java9.streams.reactive.flowvsrx;
import io.reactivex.rxjava3.core.BackpressureOverflowStrategy;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
public class RxJavaLiveVideo {
public static Disposable streamLiveVideo(long produceDelay, long consumeDelay, int bufferSize, Runnable onError) {
return Flowable
.fromStream(Stream.iterate(new VideoFrame(0), videoFrame -> {
sleep(produceDelay);
return new VideoFrame(videoFrame.getNumber() + 1);
}))
.subscribeOn(Schedulers.from(Executors.newSingleThreadScheduledExecutor()), true)
.onBackpressureBuffer(bufferSize, null, BackpressureOverflowStrategy.ERROR)
.observeOn(Schedulers.from(Executors.newSingleThreadExecutor()))
.subscribe(item -> {
sleep(consumeDelay);
}, throwable -> {
onError.run();
});
}
private static void sleep(long i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,13 @@
package com.baeldung.java9.streams.reactive.flowvsrx;
class VideoFrame {
private long number;
public VideoFrame(long number) {
this.number = number;
}
public long getNumber() {
return number;
}
}
@@ -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);
}
}
@@ -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));
}
}
+1 -1
View File
@@ -64,7 +64,7 @@
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
<url>https://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
@@ -0,0 +1,87 @@
package com.baeldung.java9.inputstream.outputstream;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertEquals;
import java.io.*;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import com.google.common.io.ByteStreams;
public class InputStreamToOutputStreamUnitTest {
/**
* Reads all bytes from an input stream and writes them to an output stream.
* @param source - input stream to copy data from
* @param target - output stream to copy data too
*/
void copy(InputStream source, OutputStream target) throws IOException {
byte[] buf = new byte[8192];
int length;
while ((length = source.read(buf)) > 0) {
target.write(buf, 0, length);
}
}
@Test
public void givenUsingJavaEight_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException {
String initialString = "Hello World!";
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
copy(inputStream, targetStream);
assertEquals(initialString, new String(targetStream.toByteArray()));
}
}
@Test
public void givenUsingJavaEight_whenCopyingLongInputStreamToOutputStream_thenCorrect() throws IOException {
String initialString = randomAlphabetic(20480);
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
copy(inputStream, targetStream);
assertEquals(initialString, new String(targetStream.toByteArray()));
}
}
@Test
public void givenUsingJavaNine_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException {
String initialString = "Hello World!";
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
inputStream.transferTo(targetStream);
assertEquals(initialString, new String(targetStream.toByteArray()));
}
}
@Test
public void givenUsingGuava_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException {
String initialString = "Hello World!";
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
ByteStreams.copy(inputStream, targetStream);
assertEquals(initialString, new String(targetStream.toByteArray()));
}
}
@Test
public void givenUsingCommonsIO_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException {
String initialString = "Hello World!";
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
IOUtils.copy(inputStream, targetStream);
assertEquals(initialString, new String(targetStream.toByteArray()));
}
}
}
@@ -4,4 +4,5 @@ This module contains complete guides about arrays in Java
### Relevant Articles:
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
- [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)
@@ -0,0 +1,42 @@
package com.baeldung.arrays;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class JavaArraysToStringUnitTest {
@Test
public void givenInstanceOfArray_whenTryingToConvertToString_thenNameOfClassIsShown() {
Object[] arrayOfObjects = { "John", 2, true };
assertTrue(arrayOfObjects.toString().startsWith("[Ljava.lang.Object;"));
}
@Test
public void givenInstanceOfArray_whenUsingArraysToStringToConvert_thenValueOfObjectsAreShown() {
Object[] arrayOfObjects = { "John", 2, true };
assertEquals(Arrays.toString(arrayOfObjects), "[John, 2, true]");
}
@Test
public void givenInstanceOfDeepArray_whenUsingArraysDeepToStringToConvert_thenValueOfInnerObjectsAreShown() {
Object[] innerArray = { "We", "Are", "Inside" };
Object[] arrayOfObjects = { "John", 2, innerArray };
assertEquals(Arrays.deepToString(arrayOfObjects), "[John, 2, [We, Are, Inside]]");
}
@Test
public void givenInstanceOfDeepArray_whenUsingStreamsToConvert_thenValueOfObjectsAreShown() {
Object[] arrayOfObjects = { "John", 2, true };
List<String> listOfString = Stream.of(arrayOfObjects)
.map(Object::toString)
.collect(Collectors.toList());
assertEquals(listOfString.toString(), "[John, 2, true]");
}
}
@@ -13,32 +13,6 @@
<name>core-java-arrays-operations-basic</name>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
@@ -66,6 +40,32 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>
@@ -14,32 +14,6 @@
<name>core-java-arrays-sorting</name>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Utilities -->
<dependency>
@@ -74,6 +48,32 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>
@@ -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)
@@ -19,31 +19,31 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.thread-weaver</groupId>
<artifactId>threadweaver</artifactId>
<version>0.2</version>
<version>${threadweaver.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.tempus-fugit</groupId>
<artifactId>tempus-fugit</artifactId>
<version>1.1</version>
<version>${tempus-fugit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.multithreadedtc</groupId>
<artifactId>multithreadedtc</artifactId>
<version>1.01</version>
<version>${multithreadedtc.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jcstress</groupId>
<artifactId>jcstress-core</artifactId>
<version>0.5</version>
<version>${jcstress-core.version}</version>
</dependency>
</dependencies>
@@ -63,8 +63,8 @@
<version>3.1</version>
<configuration>
<compilerVersion>${javac.target}</compilerVersion>
<source>${javac.target}</source>
<target>${javac.target}</target>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
@@ -99,7 +99,11 @@
</build>
<properties>
<javac.target>1.8</javac.target>
<junit.version>4.13</junit.version>
<threadweaver.version>0.2</threadweaver.version>
<tempus-fugit.version>1.1</tempus-fugit.version>
<multithreadedtc.version>1.01</multithreadedtc.version>
<jcstress-core.version>0.5</jcstress-core.version>
</properties>
</project>
@@ -13,4 +13,6 @@ 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 Exchanger in Java](https://www.baeldung.com/java-exchanger)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)
@@ -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;
}
}
@@ -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) {
@@ -0,0 +1,16 @@
package com.baeldung.thisescape;
public class ImplicitEscape {
public ImplicitEscape() {
Thread t = new Thread() {
@Override
public void run() {
System.out.println("Started...");
}
};
t.start();
}
}
@@ -0,0 +1,14 @@
package com.baeldung.thisescape;
public class LoggerRunnable implements Runnable {
public LoggerRunnable() {
Thread thread = new Thread(this); // this escapes
thread.start();
}
@Override
public void run() {
System.out.println("Started...");
}
}
@@ -0,0 +1,24 @@
package com.baeldung.thisescape;
public class SafePublication implements Runnable {
private final Thread thread;
public SafePublication() {
thread = new Thread(this);
}
@Override
public void run() {
System.out.println("Started...");
}
public void start() {
thread.start();
}
public static void main(String[] args) {
SafePublication publication = new SafePublication();
publication.start();
}
}
@@ -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());
}
}
@@ -34,4 +34,20 @@ public class BaeldungSychronizedBlockUnitTest {
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
}
@Test
public void givenHoldingTheLock_whenReentrant_thenCanAcquireItAgain() {
Object lock = new Object();
synchronized (lock) {
System.out.println("First time acquiring it");
synchronized (lock) {
System.out.println("Entering again");
synchronized (lock) {
System.out.println("And again");
}
}
}
}
}
@@ -13,3 +13,4 @@ This module contains articles about concurrent Java collections
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
- [LinkedBlockingQueue vs ConcurrentLinkedQueue](https://www.baeldung.com/java-queue-linkedblocking-concurrentlinked)
@@ -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)
+142
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>
@@ -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);
}
}
@@ -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)
@@ -1,41 +0,0 @@
package com.baeldung.weeknumber;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class WeekNumberUsingCalendar {
public int getWeekNumberFrom(String day, String dateFormat, Locale locale) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance(locale);
Date date = sdf.parse(day);
calendar.setTime(date);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
public int getWeekNumberFrom(int year, int month, int day, Locale locale) {
Calendar calendar = Calendar.getInstance(locale);
calendar.set(year, month, day);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
public int getWeekNumberFrom(int year, int month, int day, int firstDayOfWeek, int minimalDaysInFirstWeek, Locale locale) {
Calendar calendar = Calendar.getInstance(locale);
calendar.setFirstDayOfWeek(firstDayOfWeek);
calendar.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek);
calendar.set(year, month, day);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
public static void main(String[] args) {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
System.out.println(calendar.getWeekNumberFrom(2020, 2, 22, Locale.CANADA));
}
}
@@ -1,30 +0,0 @@
package com.baeldung.weeknumber;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class WeekNumberUsingLocalDate {
public Integer getWeekNumberUsingWeekFiedsFrom(String day, String dayFormat, Locale locale) {
LocalDate date = LocalDate.parse(day, DateTimeFormatter.ofPattern(dayFormat));
return date.get(WeekFields.of(locale)
.weekOfYear());
}
public Integer getWeekNumberUsinWeekFieldsFrom(int year, int month, int day, Locale locale) {
LocalDate date = LocalDate.of(year, month, day);
return date.get(WeekFields.of(locale)
.weekOfYear());
}
public Integer getWeekNumberUsingChronoFieldFrom(int year, int month, int day) {
LocalDate date = LocalDate.of(year, month, day);
return date.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
}
}
@@ -0,0 +1,64 @@
package com.baeldung.weeknumber;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.time.temporal.WeekFields;
import java.util.Calendar;
import java.util.Locale;
import org.junit.Test;
public class GetWeekNumberUnitTest {
@Test
public void givenDateUsingFieldsAndLocaleItaly_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
Calendar calendar = Calendar.getInstance(Locale.ITALY);
calendar.set(2020, 10, 22);
assertEquals(47, calendar.get(Calendar.WEEK_OF_YEAR));
}
@Test
public void givenDateUsingFieldsAndLocaleCanada_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
Calendar calendar = Calendar.getInstance(Locale.CANADA);
calendar.set(2020, 10, 22);
assertEquals(48, calendar.get(Calendar.WEEK_OF_YEAR));
}
@Test
public void givenDateUsingFieldsAndLocaleItaly_whenChangingWeekCalcSettings_thenWeekIsReturnedCorrectly() {
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.SUNDAY);
calendar.setMinimalDaysInFirstWeek(4);
calendar.set(2020, 2, 22);
assertEquals(13, calendar.get(Calendar.WEEK_OF_YEAR));
}
@Test
public void givenDateUsingChronoFields_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
LocalDate date = LocalDate.of(2020, 3, 22);
assertEquals(12, date.get(ChronoField.ALIGNED_WEEK_OF_YEAR));
}
@Test
public void givenDateUsingFieldsWithLocaleItaly_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
LocalDate date = LocalDate.of(2020, 3, 22);
assertEquals(12, date.get(WeekFields.of(Locale.ITALY)
.weekOfYear()));
}
@Test
public void givenDateUsingFieldsWithLocaleCanada_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
LocalDate date = LocalDate.of(2020, 3, 22);
assertEquals(13, date.get(WeekFields.of(Locale.CANADA)
.weekOfYear()));
}
}
@@ -1,46 +0,0 @@
package com.baeldung.weeknumber;
import static org.junit.Assert.assertEquals;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Locale;
import org.junit.Test;
public class WeekNumberUsingCalendarUnitTest {
@Test
public void givenDateInStringAndDateFormatUsingLocaleItaly_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() throws ParseException {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(12, calendar.getWeekNumberFrom("20200322", "yyyyMMdd", Locale.ITALY));
}
@Test
public void givenDateInStringAndDateFormatUsingLocaleCanada_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() throws ParseException {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(13, calendar.getWeekNumberFrom("20200322", "yyyyMMdd", Locale.CANADA));
}
@Test
public void givenDateInYearMonthDayNumbersLocaleItaly_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(12, calendar.getWeekNumberFrom(2020, 2, 22, Locale.ITALY));
}
@Test
public void givenDateInYearMonthDayNumbersLocaleItalyChangingWeekCalculationSettings_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(13, calendar.getWeekNumberFrom(2020, 2, 22, Calendar.SUNDAY, 4, Locale.ITALY));
}
@Test
public void givenDateInYearMonthDayNumbersLocaleCanada_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(13, calendar.getWeekNumberFrom(2020, 2, 22, Locale.CANADA));
}
}
@@ -1,49 +0,0 @@
package com.baeldung.weeknumber;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import org.junit.Test;
public class WeekNumberUsingLocalDateUnitTest {
@Test
public void givenDateInStringAndDateFormatUsingWeekFieldsWithLocaleItaly_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(12, localDate.getWeekNumberUsingWeekFiedsFrom("20200322", "yyyyMMdd", Locale.ITALY)
.longValue());
}
@Test
public void givenDateInStringAndDateFormatUsingWeekFieldsWithLocaleCanada_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(13, localDate.getWeekNumberUsingWeekFiedsFrom("20200322", "yyyyMMdd", Locale.CANADA)
.longValue());
}
@Test
public void givenDateInStringAndDateFormatUsingChronoFieds_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(12, localDate.getWeekNumberUsingChronoFieldFrom(2020, 3, 22)
.longValue());
}
@Test
public void givenDateInYearMonthDayNumbersUsingWeekFieldsWithLocaleItaly_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(12, localDate.getWeekNumberUsinWeekFieldsFrom(2020, 3, 22, Locale.ITALY)
.longValue());
}
@Test
public void givenDateInYearMonthDayNumbersUsingWeekFieldsWithLocaleCanada_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(13, localDate.getWeekNumberUsinWeekFieldsFrom(2020, 3, 22, Locale.CANADA)
.longValue());
}
}
@@ -0,0 +1,55 @@
package com.baeldung.exceptionininitializererror;
import org.junit.Test;
import java.lang.reflect.Constructor;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ExceptionInInitializerErrorUnitTest {
@Test
public void givenStaticVar_whenThrows_thenWrapsItInAnExceptionInInitializerError() {
assertThatThrownBy(StaticVar::new)
.isInstanceOf(ExceptionInInitializerError.class)
.hasCauseInstanceOf(RuntimeException.class);
}
@Test
public void givenStaticBlock_whenThrows_thenWrapsItInAnExceptionInInitializerError() {
assertThatThrownBy(StaticBlock::new)
.isInstanceOf(ExceptionInInitializerError.class)
.hasCauseInstanceOf(ArithmeticException.class);
}
private static class CheckedConvention {
private static Constructor<?> constructor;
static {
try {
constructor = CheckedConvention.class.getDeclaredConstructor();
} catch (NoSuchMethodException e) {
throw new ExceptionInInitializerError(e);
}
}
}
private static class StaticVar {
private static int state = initializeState();
private static int initializeState() {
throw new RuntimeException();
}
}
private static class StaticBlock {
private static int state;
static {
state = 42 / 0;
}
}
}
@@ -0,0 +1,87 @@
package com.baeldung.exceptions;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
public class TooManyOpenFilesExceptionLiveTest {
//This is not a regular UnitTest due to the fact that it depends on System.gc() to work properly.
//As we have to force the JVM to run out of file descriptors, any other tests that uses IO may fail.
//This may indirectly affect other tests that are part of the Jenkins Build.
private File tempFile;
@BeforeEach
public void setUp() throws IOException {
tempFile = File.createTempFile("testForException", "tmp");
}
@AfterEach
public void tearDown() {
//Enforce a GC to clear unreferenced files and release descriptors
System.gc();
tempFile.delete();
}
@Test
public void whenNotClosingResoures_thenIOExceptionShouldBeThrown() {
try {
for (int x = 0; x < 1000000; x++) {
FileInputStream leakyHandle = new FileInputStream(tempFile);
}
Assertions.fail("Method Should Have Failed");
} catch (IOException e) {
assertTrue(e.getMessage().toLowerCase().contains("too many open files"));
} catch (Exception e) {
Assertions.fail("Unexpected exception");
}
}
@Test
public void whenClosingResoures_thenIOExceptionShouldNotBeThrown() {
try {
for (int x = 0; x < 1000000; x++) {
FileInputStream nonLeakyHandle = null;
try {
nonLeakyHandle = new FileInputStream(tempFile);
} finally {
if (nonLeakyHandle != null) {
nonLeakyHandle.close();
}
}
}
} catch (IOException e) {
assertFalse(e.getMessage().toLowerCase().contains("too many open files"));
Assertions.fail("Method Should Not Have Failed");
} catch (Exception e) {
Assertions.fail("Unexpected exception");
}
}
@Test
public void whenUsingTryWithResoures_thenIOExceptionShouldNotBeThrown() {
try {
for (int x = 0; x < 1000000; x++) {
try (FileInputStream nonLeakyHandle = new FileInputStream(tempFile)) {
//Do something with the file
}
}
} catch (IOException e) {
assertFalse(e.getMessage().toLowerCase().contains("too many open files"));
Assertions.fail("Method Should Not Have Failed");
} catch (Exception e) {
Assertions.fail("Unexpected exception");
}
}
}
+2 -1
View File
@@ -50,7 +50,7 @@
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>2.26.3</version>
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
@@ -80,6 +80,7 @@
<properties>
<assertj.version>3.6.1</assertj.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<wiremock.version>2.26.3</wiremock.version>
</properties>
</project>
@@ -5,4 +5,5 @@ This module contains articles about core Java input/output(IO) conversions.
### Relevant Articles:
- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string)
- [Java Write an InputStream to a File](https://www.baeldung.com/convert-input-stream-to-a-file)
- [Converting a BufferedReader to a JSONObject](https://www.baeldung.com/java-bufferedreader-to-jsonobject)
- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions)
@@ -21,6 +21,11 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
</dependencies>
<build>
@@ -33,4 +38,8 @@
</resources>
</build>
<properties>
<json.version>20200518</json.version>
</properties>
</project>
@@ -0,0 +1,48 @@
package com.baeldung.bufferedreadertojsonobject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Test;
public class JavaBufferedReaderToJSONObjectUnitTest {
@Test
public void givenValidJson_whenUsingBufferedReader_thenJSONTokenerConverts() {
byte[] b = "{ \"name\" : \"John\", \"age\" : 18 }".getBytes(StandardCharsets.UTF_8);
InputStream is = new ByteArrayInputStream(b);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
JSONTokener tokener = new JSONTokener(bufferedReader);
JSONObject json = new JSONObject(tokener);
assertNotNull(json);
assertEquals("John", json.get("name"));
assertEquals(18, json.get("age"));
}
@Test
public void givenValidJson_whenUsingString_thenJSONObjectConverts() throws IOException {
byte[] b = "{ \"name\" : \"John\", \"age\" : 18 }".getBytes(StandardCharsets.UTF_8);
InputStream is = new ByteArrayInputStream(b);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
JSONObject json = new JSONObject(sb.toString());
assertNotNull(json);
assertEquals("John", json.get("name"));
assertEquals(18, json.get("age"));
}
}
@@ -72,7 +72,7 @@ public class JavaFolderSizeUnitTest {
public void whenGetFolderSizeUsingGuava_thenCorrect() {
final File folder = new File(path);
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
final Iterable<File> files = com.google.common.io.Files.fileTraverser().breadthFirst(folder);
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
assertEquals(EXPECTED_SIZE, size);
@@ -0,0 +1,5 @@
## Core Java JVM Cookbooks and Examples
This module contains articles about working with the Java Virtual Machine (JVM).
### Relevant Articles:
+43
View File
@@ -0,0 +1,43 @@
<?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-jvm-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-jvm-2</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>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>${jol-core.version}</version>
</dependency>
</dependencies>
<properties>
<assertj.version>3.6.1</assertj.version>
<jol-core.version>0.10</jol-core.version>
</properties>
</project>
@@ -0,0 +1,13 @@
package com.baeldung.arraylength;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
public class ArrayLengthUnitTest {
@Test
public void printingTheArrayLength() {
int[] ints = new int[42];
System.out.println(ClassLayout.parseInstance(ints).toPrintable());
}
}
@@ -0,0 +1,108 @@
package com.baeldung.memlayout;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;
import sun.misc.Contended;
public class MemoryLayoutUnitTest {
private volatile Object consumer;
@Test
public void printingTheVMDetails() {
System.out.println(VM.current().details());
}
@Test
public void simpleMemoryLayout() {
System.out.println(ClassLayout.parseClass(SimpleInt.class).toPrintable());
}
@Test
public void identityHashCodeMemoryLayout() {
SimpleInt instance = new SimpleInt();
System.out.println(ClassLayout.parseInstance(instance).toPrintable());
System.out.println("The identity hash code is " + System.identityHashCode(instance));
System.out.println(ClassLayout.parseInstance(instance).toPrintable());
}
@Test
public void alignmentMemoryLayout() {
System.out.println(ClassLayout.parseClass(SimpleLong.class).toPrintable());
}
@Test
public void fieldPackingMemoryLayout() {
System.out.println(ClassLayout.parseClass(FieldsArrangement.class).toPrintable());
}
@Test
public void monitorLockMemoryLayout() {
Lock lock = new Lock();
System.out.println(ClassLayout.parseInstance(lock).toPrintable());
synchronized (lock) {
System.out.println(ClassLayout.parseInstance(lock).toPrintable());
}
}
@Test
public void ageAndTenuringMemoryLayout() {
Object instance = new Object();
long lastAddr = VM.current().addressOf(instance);
ClassLayout layout = ClassLayout.parseInstance(instance);
for (int i = 0; i < 10_000; i++) {
long currentAddr = VM.current().addressOf(instance);
if (currentAddr != lastAddr) {
System.out.println(layout.toPrintable());
}
for (int j = 0; j < 10_000; j++) {
consumer = new Object();
}
lastAddr = currentAddr;
}
}
@Test
public void contendedMemoryLayout() {
System.out.println(ClassLayout.parseClass(Isolated.class).toPrintable());
}
@Test
public void arrayMemoryLayout() {
boolean[] booleans = new boolean[3];
System.out.println(ClassLayout.parseInstance(booleans).toPrintable());
}
private static class SimpleInt {
private int state;
}
private static class SimpleLong {
private long state;
}
private static class FieldsArrangement {
private boolean first;
private char second;
private double third;
private int fourth;
private boolean fifth;
}
private static class Lock {}
private static class Isolated {
@Contended
private int i;
@Contended
private long l;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.objectsize;
public class Course {
private String name;
public Course(String name) {
this.name = name;
}
}
@@ -0,0 +1,11 @@
package com.baeldung.objectsize;
public class InstrumentedSize {
public static void main(String[] args) {
String ds = "Data Structures";
Course course = new Course(ds);
System.out.println(ObjectSizeCalculator.sizeOf(course));
}
}
@@ -0,0 +1 @@
Premain-Class: com.baeldung.objectsize.ObjectSizeCalculator
@@ -0,0 +1,16 @@
package com.baeldung.objectsize;
import java.lang.instrument.Instrumentation;
public class ObjectSizeCalculator {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long sizeOf(Object o) {
return instrumentation.getObjectSize(o);
}
}
@@ -0,0 +1,40 @@
package com.baeldung.objectsize;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.info.GraphLayout;
import org.openjdk.jol.vm.VM;
public class ObjectSizeUnitTest {
@Test
public void printingTheVMDetails() {
System.out.println(VM.current().details());
}
@Test
public void printingTheProfClassLayout() {
System.out.println(ClassLayout.parseClass(Professor.class).toPrintable());
}
@Test
public void printingTheCourseClassLayout() {
System.out.println(ClassLayout.parseClass(Course.class).toPrintable());
}
@Test
public void printingACourseInstanceLayout() {
String ds = "Data Structures";
Course course = new Course(ds);
System.out.println("The shallow size is :" + VM.current().sizeOf(course));
System.out.println(ClassLayout.parseInstance(course).toPrintable());
System.out.println(ClassLayout.parseInstance(ds).toPrintable());
System.out.println(ClassLayout.parseInstance(ds.toCharArray()).toPrintable());
System.out.println(GraphLayout.parseInstance(course).totalSize());
System.out.println(GraphLayout.parseInstance(course).toFootprint());
System.out.println(GraphLayout.parseInstance(course).toPrintable());
}
}
@@ -0,0 +1,24 @@
package com.baeldung.objectsize;
import java.time.LocalDate;
import java.util.List;
public class Professor {
private String name;
private boolean tenured;
private List<Course> courses;
private int level;
private LocalDate birthDay;
private double lastEvaluation;
public Professor(String name, boolean tenured, List<Course> courses,
int level, LocalDate birthDay, double lastEvaluation) {
this.name = name;
this.tenured = tenured;
this.courses = courses;
this.level = level;
this.birthDay = birthDay;
this.lastEvaluation = lastEvaluation;
}
}
@@ -12,3 +12,7 @@ This module contains articles about working with the Java Virtual Machine (JVM).
- [Guide to System.gc()](https://www.baeldung.com/java-system-gc)
- [Runtime.getRuntime().halt() vs System.exit() in Java](https://www.baeldung.com/java-runtime-halt-vs-system-exit)
- [Adding Shutdown Hooks for JVM Applications](https://www.baeldung.com/jvm-shutdown-hooks)
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
- [What Causes java.lang.OutOfMemoryError: unable to create new native thread](https://www.baeldung.com/java-outofmemoryerror-unable-to-create-new-native-thread)
- [View Bytecode of a Class File in Java](https://www.baeldung.com/java-class-view-bytecode)
- [boolean and boolean[] Memory Layout in the JVM](https://www.baeldung.com/jvm-boolean-memory-layout)
+24 -1
View File
@@ -51,14 +51,37 @@
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-util</artifactId>
<version>${asm.version}</version>
</dependency>
<dependency>
<groupId>org.apache.bcel</groupId>
<artifactId>bcel</artifactId>
<version>${bcel.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>${jol-core.version}</version>
</dependency>
</dependencies>
<properties>
<assertj.version>3.6.1</assertj.version>
<!-- instrumentation -->
<javaassist.version>3.21.0-GA</javaassist.version>
<javaassist.version>3.27.0-GA</javaassist.version>
<esapi.version>2.1.0.1</esapi.version>
<sun.tools.version>1.8.0</sun.tools.version>
<jol-core.version>0.10</jol-core.version>
<asm.version>8.0.1</asm.version>
<bcel.version>6.5.0</bcel.version>
</properties>
</project>
@@ -0,0 +1,25 @@
package com.baeldung.boolsize;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;
public class BooleanSizeUnitTest {
@Test
public void printingTheVMDetails() {
System.out.println(VM.current().details());
}
@Test
public void printingTheBoolWrapper() {
System.out.println(ClassLayout.parseClass(BooleanWrapper.class).toPrintable());
}
@Test
public void printingTheBoolArray() {
boolean[] value = new boolean[3];
System.out.println(ClassLayout.parseInstance(value).toPrintable());
}
}
@@ -0,0 +1,5 @@
package com.baeldung.boolsize;
class BooleanWrapper {
private boolean value;
}
@@ -0,0 +1,51 @@
package com.baeldung.bytecode;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.JavaClass;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.util.TraceClassVisitor;
import javassist.ClassPool;
import javassist.NotFoundException;
import javassist.bytecode.ClassFile;
public class ViewBytecodeUnitTest {
@Test
public void whenUsingASM_thenReadBytecode() throws IOException {
ClassReader reader = new ClassReader("java.lang.Object");
StringWriter sw = new StringWriter();
TraceClassVisitor tcv = new TraceClassVisitor(new PrintWriter(sw));
reader.accept(tcv, 0);
assertTrue(sw.toString().contains("public class java/lang/Object"));
}
@Test
public void whenUsingBCEL_thenReadBytecode() throws ClassNotFoundException {
JavaClass objectClazz = Repository.lookupClass("java.lang.Object");
assertEquals(objectClazz.getClassName(), "java.lang.Object");
assertEquals(objectClazz.getMethods().length, 14);
assertTrue(objectClazz.toString().contains("public class java.lang.Object"));
}
@Test
public void whenUsingJavassist_thenReadBytecode() throws NotFoundException {
ClassPool cp = ClassPool.getDefault();
ClassFile cf = cp.get("java.lang.Object").getClassFile();
assertEquals(cf.getName(), "java.lang.Object");
assertEquals(cf.getMethods().size(), 14);
}
}
@@ -0,0 +1,40 @@
package com.baeldung.error.oom;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
public class ExecutorServiceUnitTest {
@Test
public void givenAnExecutorService_WhenMoreTasksSubmitted_ThenAdditionalTasksWait() {
// Given
int noOfThreads = 5;
ExecutorService executorService = Executors.newFixedThreadPool(noOfThreads);
Runnable runnableTask = () -> {
try {
TimeUnit.HOURS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
// When
IntStream.rangeClosed(1, 10)
.forEach(i -> executorService.submit(runnableTask));
// Then
assertThat(((ThreadPoolExecutor) executorService).getQueue()
.size(), is(equalTo(5)));
}
}
@@ -11,4 +11,6 @@ This module contains articles about core features in the Java language
- [Guide to the Java finally Keyword](https://www.baeldung.com/java-finally-keyword)
- [The Java Headless Mode](https://www.baeldung.com/java-headless-mode)
- [Comparing Long Values in Java](https://www.baeldung.com/java-compare-long-values)
- [Comparing Objects in Java](https://www.baeldung.com/java-comparing-objects)
- [Casting int to Enum in Java](https://www.baeldung.com/java-cast-int-to-enum)
- [[<-- Prev]](/core-java-modules/core-java-lang)
@@ -22,15 +22,15 @@ public class PersonWithEquals {
this.birthDate = birthDate;
}
public String firstName() {
public String getFirstName() {
return firstName;
}
public String lastName() {
public String getLastName() {
return lastName;
}
public LocalDate birthDate() {
public LocalDate getBirthDate() {
return birthDate;
}
@@ -22,6 +22,18 @@ public class PersonWithEqualsAndComparable implements Comparable<PersonWithEqual
this.birthDate = birthDate;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public LocalDate getBirthDate() {
return birthDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
@@ -23,15 +23,15 @@ public class PersonWithEqualsAndComparableUsingComparator implements Comparable<
this.birthDate = birthDate;
}
public String firstName() {
public String getFirstName() {
return firstName;
}
public String lastName() {
public String getLastName() {
return lastName;
}
public LocalDate birthDate() {
public LocalDate getBirthDate() {
return birthDate;
}
@@ -52,9 +52,9 @@ public class PersonWithEqualsAndComparableUsingComparator implements Comparable<
@Override
public int compareTo(PersonWithEqualsAndComparableUsingComparator o) {
return Comparator.comparing(PersonWithEqualsAndComparableUsingComparator::lastName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::firstName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::birthDate, Comparator.nullsLast(Comparator.naturalOrder()))
return Comparator.comparing(PersonWithEqualsAndComparableUsingComparator::getLastName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::getFirstName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::getBirthDate, Comparator.nullsLast(Comparator.naturalOrder()))
.compare(this, o);
}
}
@@ -22,6 +22,18 @@ public class PersonWithEqualsAndWrongComparable implements Comparable<PersonWith
this.birthDate = birthDate;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public LocalDate getBirthDate() {
return birthDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
@@ -8,4 +8,12 @@ public class PersonWithoutEquals {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
@@ -21,11 +21,10 @@ public enum PizzaStatus {
private static Map<Integer, PizzaStatus> timeToDeliveryToEnumValuesMapping = new HashMap<>();
static {
PizzaStatus[] pizzaStatuses = PizzaStatus.values();
for (int pizzaStatusIndex = 0; pizzaStatusIndex < pizzaStatuses.length; pizzaStatusIndex++) {
for (PizzaStatus pizzaStatus : PizzaStatus.values()) {
timeToDeliveryToEnumValuesMapping.put(
pizzaStatuses[pizzaStatusIndex].getTimeToDelivery(),
pizzaStatuses[pizzaStatusIndex]
pizzaStatus.getTimeToDelivery(),
pizzaStatus
);
}
}
@@ -20,7 +20,7 @@ class ComparatorInterfaceUnitTest {
Comparator<PersonWithEquals> compareByFirstNames = new Comparator<PersonWithEquals>() {
@Override
public int compare(PersonWithEquals o1, PersonWithEquals o2) {
return o1.firstName().compareTo(o2.firstName());
return o1.getFirstName().compareTo(o2.getFirstName());
}
};
people.sort(compareByFirstNames);
@@ -37,7 +37,7 @@ class ComparatorInterfaceUnitTest {
people.add(joe);
people.add(allan);
Comparator<PersonWithEquals> compareByFirstNames = Comparator.comparing(PersonWithEquals::firstName);
Comparator<PersonWithEquals> compareByFirstNames = Comparator.comparing(PersonWithEquals::getFirstName);
people.sort(compareByFirstNames);
assertThat(people).containsExactly(allan, joe);
@@ -63,8 +63,8 @@ class GuavaUnitTest {
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
int comparisonResult = ComparisonChain.start()
.compare(natalie.lastName(), joe.lastName())
.compare(natalie.firstName(), joe.firstName())
.compare(natalie.getLastName(), joe.getLastName())
.compare(natalie.getFirstName(), joe.getFirstName())
.result();
assertThat(comparisonResult).isPositive();
@@ -1,7 +1,12 @@
package com.baeldung.inttoenum;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.util.Arrays;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
public class IntToEnumUnitTest {
@@ -9,19 +14,33 @@ public class IntToEnumUnitTest {
@Test
public void whenIntToEnumUsingValuesMethod_thenReturnEnumObject() {
int timeToDeliveryForOrderedPizzaStatus = 5;
PizzaStatus[] pizzaStatuses = PizzaStatus.values();
PizzaStatus pizzaOrderedStatus = null;
for (int pizzaStatusIndex = 0; pizzaStatusIndex < pizzaStatuses.length; pizzaStatusIndex++) {
if (pizzaStatuses[pizzaStatusIndex].getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus) {
pizzaOrderedStatus = pizzaStatuses[pizzaStatusIndex];
for (PizzaStatus pizzaStatus : PizzaStatus.values()) {
if (pizzaStatus.getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus) {
pizzaOrderedStatus = pizzaStatus;
}
}
assertEquals(pizzaOrderedStatus, PizzaStatus.ORDERED);
assertThat(pizzaOrderedStatus).isEqualTo(PizzaStatus.ORDERED);
}
@Test
public void whenIntToEnumUsingMap_thenReturnEnumObject() {
int timeToDeliveryForOrderedPizzaStatus = 5;
assertEquals(PizzaStatus.castIntToEnum(timeToDeliveryForOrderedPizzaStatus), PizzaStatus.ORDERED);
assertThat(PizzaStatus.castIntToEnum(timeToDeliveryForOrderedPizzaStatus)).isEqualTo(PizzaStatus.ORDERED);
}
@Test
public void whenIntToEnumUsingStream_thenReturnEnumObject() {
int timeToDeliveryForOrderedPizzaStatus = 5;
Optional<PizzaStatus> pizzaStatus = Arrays.stream(PizzaStatus.values())
.filter(p -> p.getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus)
.findFirst();
assertThat(pizzaStatus).hasValue(PizzaStatus.ORDERED);
}
}
@@ -0,0 +1,6 @@
## Core Java Lang (Part 3)
This module contains articles about core features in the Java language
### Relevant Articles:
- [[<-- Prev]](/core-java-modules/core-java-lang-2)
@@ -0,0 +1,36 @@
<?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-lang-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-3</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-lang-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
</properties>
</project>
@@ -0,0 +1,5 @@
package com.baeldung.isinstancevsisassignablefrom;
public class IsoscelesTriangle extends Triangle {
}
@@ -0,0 +1,5 @@
package com.baeldung.isinstancevsisassignablefrom;
public interface Shape {
}
@@ -0,0 +1,5 @@
package com.baeldung.isinstancevsisassignablefrom;
public class Triangle implements Shape {
}
@@ -0,0 +1,67 @@
package com.baeldung.isinstancevsisassignablefrom;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class IsInstanceIsAssignableFromUnitTest {
@Test
public void whenUsingIsInstanceProperly_desiredResultsHappen() {
Shape shape = new Triangle();
Triangle triangle = new Triangle();
IsoscelesTriangle isoscelesTriangle = new IsoscelesTriangle();
Triangle isoscelesTriangle2 = new IsoscelesTriangle();
Shape nonspecificShape = null;
assertTrue(Shape.class.isInstance(shape));
assertTrue(Shape.class.isInstance(triangle));
assertTrue(Shape.class.isInstance(isoscelesTriangle));
assertTrue(Shape.class.isInstance(isoscelesTriangle2));
assertFalse(Shape.class.isInstance(nonspecificShape));
assertTrue(Triangle.class.isInstance(shape));
assertTrue(Triangle.class.isInstance(triangle));
assertTrue(Triangle.class.isInstance(isoscelesTriangle));
assertTrue(Triangle.class.isInstance(isoscelesTriangle2));
assertFalse(IsoscelesTriangle.class.isInstance(shape));
assertFalse(IsoscelesTriangle.class.isInstance(triangle));
assertTrue(IsoscelesTriangle.class.isInstance(isoscelesTriangle));
assertTrue(IsoscelesTriangle.class.isInstance(isoscelesTriangle2));
}
@Test
public void whenUsingIsAssignableFromProperly_desiredResultsHappen() {
Shape shape = new Triangle();
Triangle triangle = new Triangle();
IsoscelesTriangle isoscelesTriangle = new IsoscelesTriangle();
Triangle isoscelesTriangle2 = new IsoscelesTriangle();
assertFalse(shape.getClass().isAssignableFrom(Shape.class));
assertTrue(shape.getClass().isAssignableFrom(shape.getClass()));
assertTrue(shape.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(shape.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(shape.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
assertFalse(triangle.getClass().isAssignableFrom(Shape.class));
assertTrue(triangle.getClass().isAssignableFrom(shape.getClass()));
assertTrue(triangle.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(triangle.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(triangle.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
assertFalse(isoscelesTriangle.getClass().isAssignableFrom(Shape.class));
assertFalse(isoscelesTriangle.getClass().isAssignableFrom(shape.getClass()));
assertFalse(isoscelesTriangle.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(isoscelesTriangle.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(isoscelesTriangle.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
assertFalse(isoscelesTriangle2.getClass().isAssignableFrom(Shape.class));
assertFalse(isoscelesTriangle2.getClass().isAssignableFrom(shape.getClass()));
assertFalse(isoscelesTriangle2.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(isoscelesTriangle2.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(isoscelesTriangle2.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
}
}
@@ -6,7 +6,6 @@
- [Java 8 Math New Methods](https://www.baeldung.com/java-8-math)
- [Java 8 Unsigned Arithmetic Support](https://www.baeldung.com/java-unsigned-arithmetic)
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
- [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp)
- [Basic Calculator in Java](https://www.baeldung.com/java-basic-calculator)
- [Overflow and Underflow in Java](https://www.baeldung.com/java-overflow-underflow)
- [Obtaining a Power Set of a Set in Java](https://www.baeldung.com/java-power-set-of-a-set)
@@ -6,3 +6,4 @@ This module contains articles about generics in Java
- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors)
- [Type Erasure in Java Explained](https://www.baeldung.com/java-type-erasure)
- [Raw Types in Java](https://www.baeldung.com/raw-types-java)
- [Super Type Tokens in Java Generics](https://www.baeldung.com/java-super-type-tokens)
@@ -0,0 +1,8 @@
package com.baeldung.covariance;
public class IntegerProducer extends Producer {
@Override
public Integer produce(String input) {
return Integer.parseInt(input);
}
}

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