Merge branch 'eugenp:master' into master

This commit is contained in:
press0
2022-11-08 07:17:12 -06:00
committed by GitHub
552 changed files with 36042 additions and 1920 deletions
@@ -0,0 +1,43 @@
package com.baeldung.arrayslicing;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class SlicingArrayUnitTest {
private static final String[] LANGUAGES = new String[] { "Python", "Java", "Kotlin", "Scala", "Ruby", "Go", "Rust" };
private static final String[] JVM_LANGUAGES = new String[] { "Java", "Kotlin", "Scala" };
@Test
void givenAnArray_whenSlicingUsingStream_shouldGetExpectedResult() {
String[] result = Arrays.stream(LANGUAGES, 1, 4).toArray(String[]::new);
assertArrayEquals(JVM_LANGUAGES, result);
}
@Test
void givenAnArray_whenSlicingUsingArraysCopyOfRange_shouldGetExpectedResult() {
String[] result = Arrays.copyOfRange(LANGUAGES, 1, 4);
assertArrayEquals(JVM_LANGUAGES, result);
}
@Test
void givenAnArray_whenSlicingUsingSystemArraycopy_shouldGetExpectedResult() {
String[] result = new String[3];
System.arraycopy(LANGUAGES, 1, result, 0, 3);
assertArrayEquals(JVM_LANGUAGES, result);
String[] result2 = new String[] { "value one", "value two", "value three", "value four", "value five", "value six", "value seven" };
System.arraycopy(LANGUAGES, 1, result2, 2, 3);
assertArrayEquals(new String[] { "value one", "value two", "Java", "Kotlin", "Scala", "value six", "value seven" }, result2);
}
@Test
void givenAnArray_whenSlicingUsingArrayUtils_shouldGetExpectedResult() {
String[] result = ArrayUtils.subarray(LANGUAGES, 1, 4);
assertArrayEquals(JVM_LANGUAGES, result);
}
}
@@ -10,3 +10,4 @@ This module contains articles about Java array fundamentals. They assume no prev
- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
- [Initializing a Boolean Array in Java](https://www.baeldung.com/java-initializing-boolean-array)
@@ -10,3 +10,4 @@
- [Create an Empty Map in Java](https://www.baeldung.com/java-create-empty-map)
- [Sorting Objects in a List by Date](https://www.baeldung.com/java-sort-list-by-date)
- [Fixed Size Queue Implementations in Java](https://www.baeldung.com/java-fixed-size-queue)
- [Difference Between Java Enumeration and Iterator](https://www.baeldung.com/java-enumeration-vs-iterator)
@@ -0,0 +1,18 @@
package com.baeldung.enumerationiteratordifferences;
import java.util.Arrays;
import java.util.List;
public final class DataUtil {
private DataUtil() {
}
static List<Person> getPersons() {
Person person1 = new Person("amit", "kumar");
Person person2 = new Person("yogi", "kuki");
Person person3 = new Person("raj", "dosi");
Person person4 = new Person("prakash", "kumar");
return Arrays.asList(person1, person2, person3, person4);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.enumerationiteratordifferences;
import java.util.Enumeration;
import java.util.Vector;
import static com.baeldung.enumerationiteratordifferences.DataUtil.getPersons;
public class EnumerationExample {
public static void main(String[] args) {
Vector<Person> people = new Vector<>(getPersons());
Enumeration<Person> enumeration = people.elements();
while (enumeration.hasMoreElements()) {
System.out.println("First Name = " + enumeration.nextElement()
.getFirstName());
}
}
}
@@ -0,0 +1,17 @@
package com.baeldung.enumerationiteratordifferences;
import java.util.Iterator;
import java.util.List;
import static com.baeldung.enumerationiteratordifferences.DataUtil.getPersons;
public class IteratorExample {
public static void main(String[] args) {
List<Person> persons = getPersons();
Iterator<Person> iterator = persons.iterator();
while (iterator.hasNext()) {
System.out.println("First Name = " + iterator.next()
.getFirstName());
}
}
}
@@ -0,0 +1,27 @@
package com.baeldung.enumerationiteratordifferences;
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
@@ -27,15 +27,13 @@ class ListToStringUnitTest {
List<String> arraysAsList = Arrays.asList("ONE", "TWO", "THREE");
StringJoiner stringJoiner = new StringJoiner(",");
arraysAsList.stream()
.forEach(v -> stringJoiner.add(v));
arraysAsList.forEach(stringJoiner::add);
String commaSeparatedString = stringJoiner.toString();
assertThat(commaSeparatedString).isEqualTo("ONE,TWO,THREE");
StringJoiner stringJoinerWithDelimiterPrefixSuffix = new StringJoiner(",", "[", "]");
arraysAsList.stream()
.forEach(v -> stringJoinerWithDelimiterPrefixSuffix.add(v));
arraysAsList.forEach(stringJoinerWithDelimiterPrefixSuffix::add);
String commaSeparatedStringWithDelimiterPrefixSuffix = stringJoinerWithDelimiterPrefixSuffix.toString();
assertThat(commaSeparatedStringWithDelimiterPrefixSuffix).isEqualTo("[ONE,TWO,THREE]");
@@ -54,11 +54,11 @@
</dependencies>
<properties>
<streamex.version>0.6.5</streamex.version>
<streamex.version>0.8.1</streamex.version>
<avaitility.version>1.7.0</avaitility.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version>
<hppc.version>0.7.2</hppc.version>
<fastutil.version>8.1.0</fastutil.version>
</properties>
</project>
</project>
@@ -15,6 +15,11 @@
</parent>
<dependencies>
<dependency>
<groupId>jakarta.ws.rs</groupId>
<artifactId>jakarta.ws.rs-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
@@ -62,8 +67,8 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>
@@ -0,0 +1,43 @@
package com.baeldung.multivaluedmap;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
// Unit test for MultivaluedMap.
public class MultivaluedMapUnitTest {
// Testing MultivaluedHashMap.
@Test
public void givenMultivaluedHashMap_whenEquals_thenTrue() {
jakarta.ws.rs.core.MultivaluedMap<String, Integer> mulmap = new jakarta.ws.rs.core.MultivaluedHashMap<>();
// Mapping keys to values.
mulmap.addAll("first", 1, 2, 3);
mulmap.add(null, null);
assertNotNull(mulmap, "The MultivaluedHashMap is null!");
assertEquals(1, mulmap.getFirst("first"), "The key isn't mapped to the right values!");
assertEquals(null, mulmap.getFirst(null), "MultivaluedHashMap didn't accept null!");
}
// Testing HashMap.
@Test
public void givenHashMap_whenEquals_thenTrue() {
Map<String, Integer> map = new HashMap<>();
// Putting key-value pairs into our map.
map.put("first", 1);
map.put(null, 2);
map.put("third", null);
assertNotNull(map, "The HashMap is null!");
assertEquals(1, map.get("first"), "The key isn't mapped to the right value!");
assertEquals(2, map.get(null), "HashMap didn't accept null as key!");
assertEquals(null, map.get("third"), "HashMap didn't accept null value!");
}
}
@@ -0,0 +1,4 @@
## Relevant articles
- [Using Streams to Collect Into a TreeSet](https://www.baeldung.com/java-stream-collect-into-treeset)
- [A Guide to LinkedHashSet in Java](https://www.baeldung.com/java-linkedhashset)
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-set-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>core-java-collections-set-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
</dependencies>
<build>
<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>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
@@ -0,0 +1,36 @@
package com.baeldung.treeset.collectintotreeset;
public class Player implements Comparable<Player> {
private String name;
private int age;
private int numberOfPlayed;
private int numberOfWins;
public Player(String name, int age, int numberOfPlayed, int numberOfWins) {
this.name = name;
this.age = age;
this.numberOfPlayed = numberOfPlayed;
this.numberOfWins = numberOfWins;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getNumberOfPlayed() {
return numberOfPlayed;
}
public int getNumberOfWins() {
return numberOfWins;
}
@Override
public int compareTo(Player o) {
return Integer.compare(age, o.age);
}
}
@@ -0,0 +1,141 @@
package com.baeldung.linkedhashset;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.*;
public class LinkedHashSetUnitTest{
@Test
void whenCreatingLinkedHashSet_shouldBeEmpty(){
Set<String> linkedHashSet = new LinkedHashSet<>();
assertTrue(linkedHashSet.isEmpty());
}
@Test
void whenCreatingLinkedHashSetWithInitialCapacity_shouldBeEmpty(){
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(20);
assertTrue(linkedHashSet.isEmpty());
}
@Test
void whenCreatingLinkedHashSetWithExistingCollection_shouldContainAllElementOfCollection(){
Collection<String> data = Arrays.asList("first", "second", "third", "fourth", "fifth");
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(data);
assertFalse(linkedHashSet.isEmpty());
assertEquals(data.size(), linkedHashSet.size());
assertTrue(linkedHashSet.containsAll(data) && data.containsAll(linkedHashSet));
}
@Test
void whenCreatingLinkedHashSetWithInitialCapacityAndLoadFactor_shouldBeEmpty(){
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(20, 3);
assertTrue(linkedHashSet.isEmpty());
}
@Test
void whenAddingElement_shouldAddElement(){
Set<Integer> linkedHashSet = new LinkedHashSet<>();
assertTrue(linkedHashSet.add(0));
assertFalse(linkedHashSet.add(0));
assertTrue(linkedHashSet.contains(0));
}
@Test
void whenAddingCollection_shouldAddAllContentOfCollection(){
Collection<Integer> data = Arrays.asList(1,2,3);
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
assertTrue(linkedHashSet.addAll(data));
assertTrue(data.containsAll(linkedHashSet) && linkedHashSet.containsAll(data));
}
@Test
void whenAddingCollectionWithDuplicateElements_shouldMaintainUniqueValuesInSet(){
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add(2);
Collection<Integer> data = Arrays.asList(1, 1, 2, 3);
assertTrue(linkedHashSet.addAll(data));
assertEquals(3, linkedHashSet.size());
assertTrue(data.containsAll(linkedHashSet) && linkedHashSet.containsAll(data));
}
@Test
void whenIteratingWithIterator_assertThatElementIsPresent(){
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add(0);
linkedHashSet.add(1);
linkedHashSet.add(2);
Iterator<Integer> iterator = linkedHashSet.iterator();
for (int i = 0; i < linkedHashSet.size(); i++) {
int nextData = iterator.next();
assertEquals(i, nextData);
}
}
@Test
void whenIteratingWithSpliterator_assertThatElementIsPresent(){
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add(0);
linkedHashSet.add(1);
linkedHashSet.add(2);
Spliterator<Integer> spliterator = linkedHashSet.spliterator();
AtomicInteger counter = new AtomicInteger();
spliterator.forEachRemaining(data -> {
assertEquals(counter.get(), (int)data);
counter.getAndIncrement();
});
}
@Test
void whenRemovingAnElement_shouldRemoveElement(){
Collection<String> data = Arrays.asList("first", "second", "third", "fourth", "fifth");
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(data);
assertTrue(linkedHashSet.remove("second"));
assertFalse(linkedHashSet.contains("second"));
}
@Test
void whenRemovingAnElementGreaterThanTwo_shouldRemoveElement(){
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add(0);
linkedHashSet.add(1);
linkedHashSet.add(2);
linkedHashSet.add(3);
linkedHashSet.add(4);
linkedHashSet.removeIf(data -> data > 2);
assertFalse(linkedHashSet.contains(3));
assertFalse(linkedHashSet.contains(4));
}
@Test
void whenRemovingAnElementWithIterator_shouldRemoveElement(){
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add(0);
linkedHashSet.add(1);
linkedHashSet.add(2);
Iterator<Integer> iterator = linkedHashSet.iterator();
int elementToRemove = 1;
assertTrue(linkedHashSet.contains(elementToRemove));
while(iterator.hasNext()){
if(elementToRemove == iterator.next()){
iterator.remove();
}
}
assertFalse(linkedHashSet.contains(elementToRemove));
}
}
@@ -0,0 +1,52 @@
package com.baeldung.treeset.collectintotreeset;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
public class CollectIntoTreeSetUnitTest {
Player kai = new Player("Kai", 26, 28, 7);
Player eric = new Player("Eric", 28, 30, 11);
Player saajan = new Player("Saajan", 30, 100, 66);
Player kevin = new Player("Kevin", 24, 50, 49);
@Test
void givenAStream_whenCollectIntoTreeSetWithNaturalOrder_thenGetExpectedResult() {
String kotlin = "Kotlin";
String java = "Java";
String python = "Python";
String ruby = "Ruby";
TreeSet<String> myTreeSet = Stream.of(ruby, java, kotlin, python)
.collect(Collectors.toCollection(TreeSet::new));
assertThat(myTreeSet).containsExactly(java, kotlin, python, ruby);
}
@Test
void givenAPlayerStream_whenCollectIntoTreeSet_thenGetExpectedResult() {
TreeSet<Player> myTreeSet = Stream.of(saajan, eric, kai, kevin)
.collect(Collectors.toCollection(TreeSet::new));
assertThat(myTreeSet).containsExactly(kevin, kai, eric, saajan);
}
@Test
void givenAPlayerStream_whenCollectIntoTreeSetWithNoOfWinsComparator_thenGetExpectedResult() {
TreeSet<Player> myTreeSet = Stream.of(saajan, eric, kai, kevin)
.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingInt(Player::getNumberOfWins))));
assertThat(myTreeSet).containsExactly(kai, eric, kevin, saajan);
}
@Test
void givenAPlayerStream_whenCollectIntoTreeSetWithWinRateComparator_thenGetExpectedResult() {
TreeSet<Player> myTreeSet = Stream.of(saajan, eric, kai, kevin)
.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(player -> BigDecimal.valueOf(player.getNumberOfWins())
.divide(BigDecimal.valueOf(player.getNumberOfPlayed()), 2, RoundingMode.HALF_UP)))));
assertThat(myTreeSet).containsExactly(kai, eric, saajan, kevin);
}
}
@@ -0,0 +1,46 @@
package com.baeldung.donerunnables;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RunnableCompletionCheckerWithCompletableFuture {
private static final Logger LOGGER = LoggerFactory.getLogger(RunnableCompletionCheckerWithCompletableFuture.class);
private static final int NUMBER_OF_RUNNABLES = 5;
private static final int PAUSE_MILLIS = 1000;
private static Runnable RUNNABLE = () -> {
try {
LOGGER.info("launching runnable");
Thread.sleep(PAUSE_MILLIS);
} catch (InterruptedException e) {
}
};
public static void main(String args[]) throws InterruptedException {
List<Runnable> runnables = IntStream.range(0, NUMBER_OF_RUNNABLES)
.mapToObj(x -> RUNNABLE)
.collect(Collectors.toList());
CompletableFuture<?>[] completableFutures = runAsynchronousTasks(runnables);
LOGGER.info("Right after the creation of the completable future array, every completable future is done: {}", isEveryCompletableFutureDone(completableFutures));
Thread.sleep((NUMBER_OF_RUNNABLES + 1) * PAUSE_MILLIS);
LOGGER.info("After {} seconds, every completable future is done: {}", NUMBER_OF_RUNNABLES + 1, isEveryCompletableFutureDone(completableFutures));
}
public static CompletableFuture<?>[] runAsynchronousTasks(List<Runnable> runnables) {
return runnables.stream()
.map(CompletableFuture::runAsync)
.toArray(CompletableFuture<?>[]::new);
}
public static boolean isEveryCompletableFutureDone(CompletableFuture<?>[] completableFutures) {
return CompletableFuture.allOf(completableFutures)
.isDone();
}
}
@@ -0,0 +1,51 @@
package com.baeldung.donerunnables;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RunnableCompletionCheckerWithThreadPoolExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(RunnableCompletionCheckerWithCompletableFuture.class);
private static final int NUMBER_OF_RUNNABLES = 5;
private static final int PAUSE_MILLIS = 1000;
private static final int NUMBER_OF_THREADS = 5;
private static Runnable RUNNABLE = () -> {
try {
LOGGER.info("launching runnable");
Thread.sleep(PAUSE_MILLIS);
} catch (InterruptedException e) {
}
};
public static void main(String args[]) throws InterruptedException {
List<Runnable> runnables = IntStream.range(0, NUMBER_OF_RUNNABLES)
.mapToObj(x -> RUNNABLE)
.collect(Collectors.toList());
ThreadPoolExecutor executor = createThreadPoolExecutor(runnables);
executor.shutdown();
LOGGER.info("After a timeout of 0 seconds, every Runnable is done: {}", isEveryRunnableDone(executor, 0));
Thread.sleep(100);
LOGGER.info("After a timeout of 100 milliseconds, every Runnable is done: {}", isEveryRunnableDone(executor, 100));
Thread.sleep(2000);
LOGGER.info("After a timeout of 2 seconds, every Runnable is done: {}", isEveryRunnableDone(executor, 1500));
}
public static ThreadPoolExecutor createThreadPoolExecutor(List<Runnable> runnables) {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(NUMBER_OF_THREADS);
runnables.forEach(executor::execute);
return executor;
}
public static boolean isEveryRunnableDone(ThreadPoolExecutor executor, int timeout) throws InterruptedException {
return executor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
}
}
@@ -9,3 +9,4 @@
- [Differences Between set() and lazySet() in Java Atomic Variables](https://www.baeldung.com/java-atomic-set-vs-lazyset)
- [Volatile vs. Atomic Variables in Java](https://www.baeldung.com/java-volatile-vs-atomic)
- [What Is “Locked Ownable Synchronizers” in Thread Dump?](https://www.baeldung.com/locked-ownable-synchronizers)
- [Understanding java.lang.Thread.State: WAITING (parking)](https://www.baeldung.com/java-lang-thread-state-waiting-parking)
@@ -0,0 +1,25 @@
package com.baeldung.threadparking;
import java.util.concurrent.locks.LockSupport;
public class Application {
public static void main(String[] args) throws InterruptedException {
final Object syncObj = new Object();
Thread t = new Thread(() -> {
int acc = 0;
for (int i = 1; i <= 100; i++) {
acc += i;
}
System.out.println("Work finished");
LockSupport.park(syncObj);
System.out.println(acc);
});
t.setName("PARK-THREAD");
t.start();
// Thread.sleep(1000);
LockSupport.unpark(t);
}
}
@@ -1,4 +1,4 @@
package com.baeldung.concurrent.daemon;
package com.baeldung.concurrent.startathread;
public class MultipleThreadsExample {
public static void main(String[] args) {
@@ -1,4 +1,4 @@
package com.baeldung.concurrent.daemon;
package com.baeldung.concurrent.startathread;
public class NewThread extends Thread {
public void run() {
@@ -1,4 +1,4 @@
package com.baeldung.concurrent.daemon;
package com.baeldung.concurrent.startathread;
public class SingleThreadExample {
public static void main(String[] args) {
@@ -0,0 +1,39 @@
package com.baeldung.concurrent.startathread;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerDemoExample {
private void scheduleOnce() {
TimerTask task = new TimerTask() {
public void run() {
System.out.println("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread()
.getName());
}
};
Timer timer = new Timer("Timer");
long delay = 1000L;
timer.schedule(task, delay);
}
private void scheduleRecurrently() {
TimerTask task = new TimerTask() {
public void run() {
System.out.println("Recurrent Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread()
.getName());
}
};
Timer timer = new Timer("Timer");
long delay = 1000L;
final long period = 1000L;
timer.scheduleAtFixedRate(task, delay, period);
}
public static void main(String[] args) {
TimerDemoExample timerDemoExample = new TimerDemoExample();
timerDemoExample.scheduleOnce();
timerDemoExample.scheduleRecurrently();
}
}
@@ -2,38 +2,40 @@ package com.baeldung.concurrent.waitandnotify;
public class Data {
private String packet;
// True if receiver should wait
// False if sender should wait
private boolean transfer = true;
public synchronized String receive() {
while (transfer) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread Interrupted");
Thread.currentThread()
.interrupt();
System.err.println("Thread Interrupted");
}
}
transfer = true;
String returnPacket = packet;
notifyAll();
return returnPacket;
}
public synchronized void send(String packet) {
while (!transfer) {
try {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread Interrupted");
Thread.currentThread()
.interrupt();
System.err.println("Thread Interrupted");
}
}
transfer = false;
this.packet = packet;
notifyAll();
}
@@ -5,7 +5,7 @@ public class NetworkDriver {
Data data = new Data();
Thread sender = new Thread(new Sender(data));
Thread receiver = new Thread(new Receiver(data));
sender.start();
receiver.start();
}
@@ -4,24 +4,24 @@ import java.util.concurrent.ThreadLocalRandom;
public class Receiver implements Runnable {
private Data load;
public Receiver(Data load) {
this.load = load;
}
public void run() {
for(String receivedMessage = load.receive();
!"End".equals(receivedMessage) ;
receivedMessage = load.receive()) {
for (String receivedMessage = load.receive(); !"End".equals(receivedMessage); receivedMessage = load.receive()) {
System.out.println(receivedMessage);
//Thread.sleep() to mimic heavy server-side processing
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
Thread.sleep(ThreadLocalRandom.current()
.nextInt(1000, 5000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread Interrupted");
Thread.currentThread()
.interrupt();
System.err.println("Thread Interrupted");
}
}
}
@@ -4,29 +4,25 @@ import java.util.concurrent.ThreadLocalRandom;
public class Sender implements Runnable {
private Data data;
public Sender(Data data) {
this.data = data;
}
public void run() {
String packets[] = {
"First packet",
"Second packet",
"Third packet",
"Fourth packet",
"End"
};
String packets[] = { "First packet", "Second packet", "Third packet", "Fourth packet", "End" };
for (String packet : packets) {
data.send(packet);
//Thread.sleep() to mimic heavy server-side processing
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
Thread.sleep(ThreadLocalRandom.current()
.nextInt(1000, 5000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread Interrupted");
Thread.currentThread()
.interrupt();
System.err.println("Thread Interrupted");
}
}
}
@@ -1,4 +1,4 @@
package com.baeldung.thread.join;
package com.baeldung.concurrent.threadjoin;
import org.junit.Ignore;
import org.junit.Test;
@@ -21,49 +21,47 @@ public class ThreadJoinUnitTest {
SampleThread(int processingCount) {
this.processingCount = processingCount;
LOGGER.debug("Thread " + this.getName() + " created");
LOGGER.info("Thread " + this.getName() + " created");
}
@Override
public void run() {
LOGGER.debug("Thread " + this.getName() + " started");
LOGGER.info("Thread " + this.getName() + " started");
while (processingCount > 0) {
try {
Thread.sleep(1000); // Simulate some work being done by thread
} catch (InterruptedException e) {
LOGGER.debug("Thread " + this.getName() + " interrupted.");
LOGGER.info("Thread " + this.getName() + " interrupted.");
}
processingCount--;
LOGGER.debug("Inside Thread " + this.getName() + ", processingCount = " + processingCount);
LOGGER.info("Inside Thread " + this.getName() + ", processingCount = " + processingCount);
}
LOGGER.debug("Thread " + this.getName() + " exiting");
LOGGER.info("Thread " + this.getName() + " exiting");
}
}
@Test
public void givenNewThread_whenJoinCalled_returnsImmediately() throws InterruptedException {
Thread t1 = new SampleThread(0);
LOGGER.debug("Invoking join.");
LOGGER.info("Invoking join");
t1.join();
LOGGER.debug("Returned from join");
LOGGER.debug("Thread state is" + t1.getState());
LOGGER.info("Returned from join");
LOGGER.info("Thread state is" + t1.getState());
assertFalse(t1.isAlive());
}
@Test
public void givenStartedThread_whenJoinCalled_waitsTillCompletion()
throws InterruptedException {
public void givenStartedThread_whenJoinCalled_waitsTillCompletion() throws InterruptedException {
Thread t2 = new SampleThread(1);
t2.start();
LOGGER.debug("Invoking join.");
LOGGER.info("Invoking join");
t2.join();
LOGGER.debug("Returned from join");
LOGGER.info("Returned from join");
assertFalse(t2.isAlive());
}
@Test
public void givenStartedThread_whenTimedJoinCalled_waitsUntilTimedout()
throws InterruptedException {
public void givenStartedThread_whenTimedJoinCalled_waitsUntilTimedout() throws InterruptedException {
Thread t3 = new SampleThread(10);
t3.start();
t3.join(1000);
@@ -72,19 +70,17 @@ public class ThreadJoinUnitTest {
@Test
@Ignore
public void givenThreadTerminated_checkForEffect_notGuaranteed()
throws InterruptedException {
public void givenThreadTerminated_checkForEffect_notGuaranteed() throws InterruptedException {
SampleThread t4 = new SampleThread(10);
t4.start();
//not guaranteed to stop even if t4 finishes.
//not guaranteed to stop even if t4 finishes.
do {
} while (t4.processingCount > 0);
}
@Test
public void givenJoinWithTerminatedThread_checkForEffect_guaranteed()
throws InterruptedException {
public void givenJoinWithTerminatedThread_checkForEffect_guaranteed() throws InterruptedException {
SampleThread t4 = new SampleThread(10);
t4.start();
do {
@@ -16,24 +16,24 @@ public class NetworkIntegrationTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private String expected;
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@Before
public void setUpExpectedOutput() {
StringWriter expectedStringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(expectedStringWriter);
printWriter.println("First packet");
printWriter.println("Second packet");
printWriter.println("Third packet");
printWriter.println("Fourth packet");
printWriter.close();
expected = expectedStringWriter.toString();
}
@@ -42,25 +42,26 @@ public class NetworkIntegrationTest {
System.setOut(null);
System.setErr(null);
}
@Test
public void givenSenderAndReceiver_whenSendingPackets_thenNetworkSynchronized() {
Data data = new Data();
Thread sender = new Thread(new Sender(data));
Thread receiver = new Thread(new Receiver(data));
sender.start();
receiver.start();
//wait for sender and receiver to finish before we test against expected
try {
sender.join();
receiver.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread Interrupted");
Thread.currentThread()
.interrupt();
System.err.println("Thread Interrupted");
}
assertEquals(expected, outContent.toString());
}
}

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