Merge branch 'BAEL-16646' into BAEL-16646-2

# Conflicts:
#	core-java-modules/pom.xml
#	java-dates/README.md
This commit is contained in:
Alessio Stalla
2019-10-13 09:46:38 +02:00
738 changed files with 4247 additions and 1809 deletions

1
.gitignore vendored
View File

@@ -84,3 +84,4 @@ software-security/sql-injection-samples/derby.log
spring-soap/src/main/java/com/baeldung/springsoap/gen/
/report-*.json
transaction.log
*-shell.log

View File

@@ -0,0 +1,54 @@
package com.baeldung.algorithms.breadthfirstsearch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class BreadthFirstSearchAlgorithm {
private static final Logger LOGGER = LoggerFactory.getLogger(BreadthFirstSearchAlgorithm.class);
public static <T> Optional<Tree<T>> search(T value, Tree<T> root) {
Queue<Tree<T>> queue = new ArrayDeque<>();
queue.add(root);
Tree<T> currentNode;
while (!queue.isEmpty()) {
currentNode = queue.remove();
LOGGER.info("Visited node with value: {}", currentNode.getValue());
if (currentNode.getValue().equals(value)) {
return Optional.of(currentNode);
} else {
queue.addAll(currentNode.getChildren());
}
}
return Optional.empty();
}
public static <T> Optional<Node<T>> search(T value, Node<T> start) {
Queue<Node<T>> queue = new ArrayDeque<>();
queue.add(start);
Node<T> currentNode;
Set<Node<T>> alreadyVisited = new HashSet<>();
while (!queue.isEmpty()) {
currentNode = queue.remove();
LOGGER.info("Visited node with value: {}", currentNode.getValue());
if (currentNode.getValue().equals(value)) {
return Optional.of(currentNode);
} else {
alreadyVisited.add(currentNode);
queue.addAll(currentNode.getNeighbors());
queue.removeAll(alreadyVisited);
}
}
return Optional.empty();
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.algorithms.breadthfirstsearch;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Node<T> {
private T value;
private Set<Node<T>> neighbors;
public Node(T value) {
this.value = value;
this.neighbors = new HashSet<>();
}
public T getValue() {
return value;
}
public Set<Node<T>> getNeighbors() {
return Collections.unmodifiableSet(neighbors);
}
public void connect(Node<T> node) {
if (this == node) throw new IllegalArgumentException("Can't connect node to itself");
this.neighbors.add(node);
node.neighbors.add(this);
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.algorithms.breadthfirstsearch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Tree<T> {
private T value;
private List<Tree<T>> children;
private Tree(T value) {
this.value = value;
this.children = new ArrayList<>();
}
public static <T> Tree<T> of(T value) {
return new Tree<>(value);
}
public T getValue() {
return value;
}
public List<Tree<T>> getChildren() {
return Collections.unmodifiableList(children);
}
public Tree<T> addChild(T value) {
Tree<T> newChild = new Tree<>(value);
children.add(newChild);
return newChild;
}
}

View File

@@ -0,0 +1,86 @@
package com.baeldung.algorithms.breadthfirstsearch;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class BreadthFirstSearchAlgorithmUnitTest {
private Tree<Integer> root;
private Tree<Integer> rootFirstChild;
private Tree<Integer> depthMostChild;
private Tree<Integer> rootSecondChild;
private Node<Integer> start;
private Node<Integer> firstNeighbor;
private Node<Integer> firstNeighborNeighbor;
private Node<Integer> secondNeighbor;
@Test
void givenTree_whenSearchTen_thenRoot() {
initTree();
assertThat(BreadthFirstSearchAlgorithm.search(10, root)).isPresent().contains(root);
}
@Test
void givenTree_whenSearchThree_thenDepthMostValue() {
initTree();
assertThat(BreadthFirstSearchAlgorithm.search(3, root)).isPresent().contains(depthMostChild);
}
@Test
void givenTree_whenSearchFour_thenRootSecondChild() {
initTree();
assertThat(BreadthFirstSearchAlgorithm.search(4, root)).isPresent().contains(rootSecondChild);
}
@Test
void givenTree_whenSearchFive_thenNotFound() {
initTree();
assertThat(BreadthFirstSearchAlgorithm.search(5, root)).isEmpty();
}
private void initTree() {
root = Tree.of(10);
rootFirstChild = root.addChild(2);
depthMostChild = rootFirstChild.addChild(3);
rootSecondChild = root.addChild(4);
}
@Test
void givenNode_whenSearchTen_thenStart() {
initNode();
assertThat(BreadthFirstSearchAlgorithm.search(10, firstNeighborNeighbor)).isPresent().contains(start);
}
@Test
void givenNode_whenSearchThree_thenNeighborNeighbor() {
initNode();
assertThat(BreadthFirstSearchAlgorithm.search(3, firstNeighborNeighbor)).isPresent().contains(firstNeighborNeighbor);
}
@Test
void givenNode_whenSearchFour_thenSecondNeighbor() {
initNode();
assertThat(BreadthFirstSearchAlgorithm.search(4, firstNeighborNeighbor)).isPresent().contains(secondNeighbor);
}
@Test
void givenNode_whenSearchFive_thenNotFound() {
initNode();
assertThat(BreadthFirstSearchAlgorithm.search(5, firstNeighborNeighbor)).isEmpty();
}
private void initNode() {
start = new Node<>(10);
firstNeighbor = new Node<>(2);
start.connect(firstNeighbor);
firstNeighborNeighbor = new Node<>(3);
firstNeighbor.connect(firstNeighborNeighbor);
firstNeighborNeighbor.connect(start);
secondNeighbor = new Node<>(4);
start.connect(secondNeighbor);
}
}

View File

@@ -1,7 +1,6 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>animal-sniffer-mvn-plugin</artifactId>
<version>1.0-SNAPSHOT</version>
<name>animal-sniffer-mvn-plugin</name>

View File

@@ -14,12 +14,6 @@
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
@@ -46,15 +40,6 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
@@ -79,8 +64,6 @@
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<compiler-plugin.version>3.5</compiler-plugin.version>
<avro.version>1.8.2</avro.version>
<slf4j.version>1.7.25</slf4j.version>
</properties>

View File

@@ -1,7 +1,6 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>apache-fop</artifactId>
<version>0.1-SNAPSHOT</version>
<name>apache-fop</name>

View File

@@ -19,26 +19,8 @@
<artifactId>geode-core</artifactId>
<version>${geode.core}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<geode.core>1.6.0</geode.core>
</properties>

View File

@@ -1,7 +1,6 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>apache-meecrowave</artifactId>
<version>0.0.1</version>
<name>apache-meecrowave</name>
@@ -38,13 +37,6 @@
<version>${meecrowave-junit.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@@ -5,7 +5,6 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung.examples.olingo2</groupId>
<artifactId>olingo2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>olingo2</name>
<description>Sample Olingo 2 Project</description>

View File

@@ -24,8 +24,6 @@
</dependencies>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<pulsar-client.version>2.1.1-incubating</pulsar-client.version>
<pulsar-client.version>2.1.1-incubating</pulsar-client.version>
</properties>
</project>

View File

@@ -1,7 +1,6 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>apache-solrj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-solrj</name>

View File

@@ -2,7 +2,6 @@
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>
<groupId>com.baeldung</groupId>
<artifactId>apache-spark</artifactId>
<version>1.0-SNAPSHOT</version>
<name>apache-spark</name>
@@ -59,15 +58,6 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
@@ -95,7 +85,6 @@
<org.apache.spark.spark-streaming-kafka.version>2.3.0</org.apache.spark.spark-streaming-kafka.version>
<com.datastax.spark.spark-cassandra-connector.version>2.3.0</com.datastax.spark.spark-cassandra-connector.version>
<com.datastax.spark.spark-cassandra-connector-java.version>1.5.2</com.datastax.spark.spark-cassandra-connector-java.version>
<maven-compiler-plugin.version>3.2</maven-compiler-plugin.version>
</properties>
</project>

View File

@@ -1,7 +1,6 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<version>0.1-SNAPSHOT</version>
<artifactId>apache-velocity</artifactId>
<name>apache-velocity</name>

View File

@@ -2,7 +2,6 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>aws-lambda</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>aws-lambda</name>
@@ -88,7 +87,6 @@
<properties>
<json-simple.version>1.1.1</json-simple.version>
<org.json.version>20180130</org.json.version>
<commons-io.version>2.5</commons-io.version>
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>

View File

@@ -1,7 +1,6 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>aws</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>aws</name>

View File

@@ -30,7 +30,6 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring-boot.version}</version>
<scope>compile</scope>
</dependency>

View File

@@ -2,7 +2,6 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>azure</artifactId>
<version>0.1</version>
<name>azure</name>

View File

@@ -0,0 +1,72 @@
package com.baeldung.findastring;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.collections4.IteratorUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class FindAStringInGivenList {
public List<String> findUsingLoopWithRegex(String search, List<String> list) {
List<String> matches = new ArrayList<String>();
String pattern = ".*"+search+".*";
Pattern p = Pattern.compile(pattern);
for(String str: list) {
if (p.matcher(str).matches()) {
matches.add(str);
}
}
return matches;
}
public List<String> findUsingLoop(String search, List<String> list) {
List<String> matches = new ArrayList<String>();
for(String str: list) {
if (str.contains(search)) {
matches.add(str);
}
}
return matches;
}
public List<String> findUsingStream(String search, List<String> list) {
List<String> matchingElements =
list.stream()
.filter(str -> str.trim().contains(search))
.collect(Collectors.toList());
return matchingElements;
}
public List<String> findUsingGuava(String search, List<String> list) {
Iterable<String> result = Iterables.filter(list, Predicates.containsPattern(search));
return Lists.newArrayList(result.iterator());
}
public List<String> findUsingCommonsCollection(String search, List<String> list) {
Iterable<String> result = IterableUtils.filteredIterable(list, new org.apache.commons.collections4.Predicate<String>() {
public boolean evaluate(String listElement) {
return listElement.contains(search);
}
});
return IteratorUtils.toList(result.iterator());
}
}

View File

@@ -0,0 +1,62 @@
package com.baeldung.findastring;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class FindAStringInListUnitTest {
private static List<String> list = new ArrayList<>();
static {
list.add("Jack and Jill");
list.add("James and Sarah");
list.add("Sam and Louise");
list.add("Jack");
list.add("");
}
private static FindAStringInGivenList findAStringInGivenList = new FindAStringInGivenList();
@Test
public void givenAString_whenFoundUsingLoopWithRegex_thenReturnList() {
List matchingElements = findAStringInGivenList.findUsingLoopWithRegex("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
@Test
public void givenAString_whenFoundUsingLoop_thenReturnList() {
List matchingElements = findAStringInGivenList.findUsingLoop("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
@Test
public void givenAString_whenFoundUsingStream_thenReturnList(){
List matchingElements = findAStringInGivenList.findUsingStream("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
@Test
public void givenAString_whenFoundUsingCommonsCollection_thenReturnList(){
List matchingElements = findAStringInGivenList.findUsingCommonsCollection("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
@Test
public void givenAString_whenFoundUsingGuava_thenReturnList(){
List matchingElements = findAStringInGivenList.findUsingGuava("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
}

View File

@@ -0,0 +1,19 @@
=========
## Core Java Concurrency Advanced Examples
This module contains articles about advanced topics about multithreading with core Java.
### Relevant Articles:
- [Semaphores in Java](https://www.baeldung.com/java-semaphore)
- [Daemon Threads in Java](https://www.baeldung.com/java-daemon-thread)
- [Priority-based Job Scheduling in Java](https://www.baeldung.com/java-priority-job-schedule)
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)
- [Print Even and Odd Numbers Using 2 Threads](https://www.baeldung.com/java-even-odd-numbers-with-2-threads)
- [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch)
- [Guide to the Fork/Join Framework in Java](https://www.baeldung.com/java-fork-join)
- [Guide to ThreadLocalRandom in Java](https://www.baeldung.com/java-thread-local-random)
- [The Thread.join() Method in Java](https://www.baeldung.com/java-thread-join)
- [Passing Parameters to Java Threads](https://www.baeldung.com/java-thread-parameters)
[[<-- previous]](/core-java-modules/core-java-concurrency-advanced)[[next -->]](/core-java-modules/core-java-concurrency-advanced-3)

View File

@@ -0,0 +1,59 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>core-java-concurrency-advanced-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-advanced-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-concurrency-advanced-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@@ -4,6 +4,7 @@ import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class CyclicBarrierResetExample {
@@ -36,6 +37,11 @@ public class CyclicBarrierResetExample {
});
}
es.shutdown();
try {
es.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return updateCount.get();
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.concurrent.daemon;
public class NewThread extends Thread {
public void run() {
long startTime = System.currentTimeMillis();
while (true) {
for (int i = 0; i < 10; i++) {
System.out.println(this.getName() + ": New Thread is running..." + i);
try {
//Wait for one sec so it doesn't print too fast
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// prevent the Thread to run forever. It will finish it's execution after 2 seconds
if (System.currentTimeMillis() - startTime > 2000) {
Thread.currentThread().interrupt();
break;
}
}
}
}

View File

@@ -1,4 +1,4 @@
package com.baeldung.concurrent.parameter;
package com.baeldung.concurrent.parameters;
import java.util.concurrent.Callable;
import java.util.stream.IntStream;

View File

@@ -1,4 +1,4 @@
package com.baeldung.concurrent.parameter;
package com.baeldung.concurrent.parameters;
import java.util.concurrent.Callable;
import java.util.stream.IntStream;

View File

@@ -1,14 +1,13 @@
package com.baeldung.parameters;
package com.baeldung.concurrent.parameters;
import com.baeldung.concurrent.parameter.AverageCalculator;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ParameterizedThreadUnitTest {

View File

@@ -1,4 +1,4 @@
package com.baeldung.java8;
package com.baeldung.forkjoin;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

View File

@@ -0,0 +1,9 @@
=========
## Core Java Concurrency Advanced Examples
This module contains articles about advanced topics about multithreading with core Java.
### Relevant Articles:
[[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@@ -0,0 +1,33 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>core-java-concurrency-advanced-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-advanced-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
</dependencies>
<build>
<finalName>core-java-concurrency-advanced-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
</properties>
</project>

View File

@@ -1,25 +1,16 @@
## Core Java Concurrency Advanced Examples
This module contains articles about advanced concurrency in core Java.
This module contains articles about advanced topics about multithreading with core Java.
### Relevant Articles:
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch)
- [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks)
- [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal)
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
- [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers)
- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
- [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables)
- [CyclicBarrier in Java](http://www.baeldung.com/java-cyclic-barrier)
- [Guide to the Volatile Keyword in Java](http://www.baeldung.com/java-volatile)
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)
- [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule)
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)
- [Print Even and Odd Numbers Using 2 Threads](https://www.baeldung.com/java-even-odd-numbers-with-2-threads)
- [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch)
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
- [Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join)
- [Passing Parameters to Java Threads](https://www.baeldung.com/java-thread-parameters)
- [Introduction to Thread Pools in Java](https://www.baeldung.com/thread-pool-java-and-guava)
- [Guide to CountDownLatch in Java](https://www.baeldung.com/java-countdown-latch)
- [Guide to java.util.concurrent.Locks](https://www.baeldung.com/java-concurrent-locks)
- [An Introduction to ThreadLocal in Java](https://www.baeldung.com/java-threadlocal)
- [LongAdder and LongAccumulator in Java](https://www.baeldung.com/java-longadder-and-longaccumulator)
- [The Dining Philosophers Problem in Java](https://www.baeldung.com/java-dining-philoshophers)
- [Guide to the Java Phaser](https://www.baeldung.com/java-phaser)
- [An Introduction to Atomic Variables in Java](https://www.baeldung.com/java-atomic-variables)
- [CyclicBarrier in Java](https://www.baeldung.com/java-cyclic-barrier)
- [Guide to the Volatile Keyword in Java](https://www.baeldung.com/java-volatile)
- More Articles: [[next -->]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@@ -47,16 +47,6 @@
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
</dependencies>
<build>
@@ -78,8 +68,6 @@
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
</properties>
</project>

View File

@@ -4,6 +4,7 @@ import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class CyclicBarrierCompletionMethodExample {
@@ -35,6 +36,11 @@ public class CyclicBarrierCompletionMethodExample {
});
}
es.shutdown();
try {
es.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return updateCount.get();
}

View File

@@ -12,9 +12,11 @@ public class SemaPhoreDemo {
System.out.println("Number of threads waiting to acquire: " + semaphore.getQueueLength());
if (semaphore.tryAcquire()) {
semaphore.acquire();
try {
// perform some critical operations
semaphore.release();
} finally {
semaphore.release();
}
}
}

View File

@@ -0,0 +1,179 @@
package com.baeldung.file;
import org.junit.Test;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class FileClassDemoUnitTest {
@Test
public void givenDirectoryCreated_whenMkdirIsInvoked_thenDirectoryIsDeleted() {
File directory = new File("testDirectory");
if (!directory.isDirectory() || !directory.exists()) {
directory.mkdir();
}
assertTrue(directory.delete());
}
@Test
public void givenFileCreated_whenCreateNewFileIsInvoked_thenFileIsDeleted() throws IOException {
File file = new File("testFile.txt");
if (!file.isFile() || !file.exists()) {
file.createNewFile();
}
assertTrue(file.delete());
}
@Test
public void givenFileCreated_whenCreateNewFileInvoked_thenMetadataIsAsExpected() throws IOException {
// different Operating systems have different separator characters
String separatorCharacter = System.getProperty("file.separator");
File parentDirectory = makeDirectory("filesDirectory");
File childFile = new File(parentDirectory, "file1.txt");
childFile.createNewFile();
assertTrue(childFile.getName().equals("file1.txt"));
assertTrue(childFile.getParentFile().getName().equals(parentDirectory.getName()));
assertTrue(childFile.getPath().equals(parentDirectory.getPath() + separatorCharacter + "file1.txt"));
removeDirectory(parentDirectory);
}
@Test(expected = FileNotFoundException.class)
public void givenReadOnlyFileCreated_whenCreateNewFileInvoked_thenFileCannotBeWrittenTo() throws IOException {
File parentDirectory = makeDirectory("filesDirectory");
File childFile = new File(parentDirectory, "file1.txt");
childFile.createNewFile();
childFile.setWritable(false);
FileOutputStream fos = new FileOutputStream(childFile);
fos.write("Hello World".getBytes()); // write operation
fos.flush();
fos.close();
removeDirectory(parentDirectory);
}
@Test(expected = FileNotFoundException.class)
public void givenWriteOnlyFileCreated_whenCreateNewFileInvoked_thenFileCannotBeReadFrom() throws IOException {
File parentDirectory = makeDirectory("filesDirectory");
File childFile = new File(parentDirectory, "file1.txt");
childFile.createNewFile();
childFile.setReadable(false);
FileInputStream fis = new FileInputStream(childFile);
fis.read(); // read operation
fis.close();
removeDirectory(parentDirectory);
}
@Test
public void givenFilesCreatedInDirectory_whenCreateNewFileInvoked_thenTheyCanBeListedAsExpected() throws IOException {
File directory = makeDirectory("filtersDirectory");
File csvFile = new File(directory, "csvFile.csv");
csvFile.createNewFile();
File txtFile = new File(directory, "txtFile.txt");
txtFile.createNewFile();
//normal listing
assertEquals(2, directory.list().length);
//filtered listing
FilenameFilter csvFilter = (dir, ext) -> ext.endsWith(".csv");
assertEquals(1, directory.list(csvFilter).length);
removeDirectory(directory);
}
@Test
public void givenDirectoryIsCreated_whenMkdirInvoked_thenDirectoryCanBeRenamed() {
File source = makeDirectory("source");
File destination = makeDirectory("destination");
source.renameTo(destination);
assertFalse(source.isDirectory());
assertTrue(destination.isDirectory());
removeDirectory(destination);
}
@Test
public void givenDataIsWrittenToFile_whenWriteIsInvoked_thenFreeSpaceOnSystemDecreases() throws IOException {
String name = System.getProperty("user.home") + System.getProperty("file.separator") + "test";
File testDir = makeDirectory(name);
File sample = new File(testDir, "sample.txt");
long freeSpaceBeforeWrite = testDir.getFreeSpace();
writeSampleDataToFile(sample);
long freeSpaceAfterWrite = testDir.getFreeSpace();
assertTrue(freeSpaceAfterWrite < freeSpaceBeforeWrite);
removeDirectory(testDir);
}
private static File makeDirectory(String directoryName) {
File directory = new File(directoryName);
directory.mkdir();
if (directory.isDirectory()) {
return directory;
}
throw new RuntimeException("Directory not created for " + directoryName);
}
private static void removeDirectory(File directory) {
// make sure you don't delete your home directory here
if (directory.getPath().equals(System.getProperty("user.home"))) {
return;
}
// remove directory and its files from system
if (directory != null && directory.exists()) {
// delete all files inside the directory
File[] filesInDirectory = directory.listFiles();
if (filesInDirectory != null) {
List<File> files = Arrays.asList(filesInDirectory);
files.forEach(f -> deleteFile(f));
}
// finally delete the directory itself
deleteFile(directory);
}
}
private static void deleteFile(File fileToDelete) {
if (fileToDelete != null && fileToDelete.exists()) {
fileToDelete.delete();
}
}
private static void writeSampleDataToFile(File sample) throws IOException {
//write sample text to file
try (FileOutputStream out = new FileOutputStream(sample)) {
for (int i = 1; i <= 100000; i++) {
String sampleText = "Sample line number " + i + "\n";
out.write(sampleText.getBytes());
}
}
}
}

View File

@@ -35,9 +35,9 @@ public class MethodReferenceUnitTest {
public void referenceToInstanceMethodOfArbitratyObjectOfParticularType() {
List<Integer> numbers = Arrays.asList(5, 3, 50, 24, 40, 2, 9, 18);
numbers.stream()
.sorted((a, b) -> Integer.compare(a, b));
.sorted((a, b) -> a.compareTo(b));
numbers.stream()
.sorted(Integer::compare);
.sorted(Integer::compareTo);
}
@Test

View File

@@ -5,3 +5,4 @@
### Relevant Articles:
- [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)

View File

@@ -7,7 +7,6 @@ This module contains articles about Object-oriented programming (OOP) in Java
- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error)
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
- [Raw Types in Java](https://www.baeldung.com/raw-types-java)
- [Java private Access Modifier](https://www.baeldung.com/java-private-keyword)
- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces)
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
- [Immutable Objects in Java](https://www.baeldung.com/java-immutable-object)

View File

@@ -9,4 +9,9 @@ This module contains articles about Object-oriented programming (OOP) in Java
- [Guide to the this Java Keyword](https://www.baeldung.com/java-this)
- [Java Public Access Modifier](https://www.baeldung.com/java-public-keyword)
- [Composition, Aggregation and Association in Java](https://www.baeldung.com/java-composition-aggregation-association)
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
- [A Guide to Inner Interfaces in Java](https://www.baeldung.com/java-inner-interfaces)
- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects)
- [Java Interfaces](https://www.baeldung.com/java-interfaces)
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
- [[<-- Prev]](/core-java-modules/core-java-lang-oop-2)

View File

@@ -1,7 +1,6 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>core-java-lang-oop-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-oop-3</name>
@@ -15,6 +14,24 @@
</parent>
<dependencies>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
@@ -23,4 +40,18 @@
</dependency>
</dependencies>
<build>
<finalName>core-java-lang-oop-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@@ -1,4 +1,4 @@
package com.baeldung.interfaces;
package com.baeldung.innerinterfaces;
import java.util.ArrayList;
import java.util.List;

View File

@@ -1,4 +1,4 @@
package com.baeldung.interfaces;
package com.baeldung.innerinterfaces;
public class Customer {
public interface List {

View File

@@ -14,13 +14,13 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.LoggerFactory;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.List;
/**
* Created by madhumita.g on 01-08-2018.
*/

View File

@@ -1,11 +1,13 @@
package com.baeldung.interfaces;
import static org.junit.Assert.assertEquals;
package com.baeldung.innerinterfaces;
import com.baeldung.innerinterfaces.CommaSeparatedCustomers;
import com.baeldung.innerinterfaces.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static org.junit.Assert.assertEquals;
@RunWith(JUnit4.class)
public class InnerInterfaceUnitTest {
@Test

View File

@@ -15,7 +15,7 @@ public class Enclosing {
@Test
public void test() {
Enclosing.StaticNested nested = new Enclosing.StaticNested();
StaticNested nested = new StaticNested();
nested.run();
}
}

View File

@@ -23,7 +23,7 @@ public class NewOuter {
@Test
public void test() {
NewOuter outer = new NewOuter();
NewOuter.InnerClass inner = outer.new InnerClass();
InnerClass inner = outer.new InnerClass();
inner.run();
}

View File

@@ -14,7 +14,7 @@ public class Outer {
@Test
public void test() {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
Inner inner = outer.new Inner();
inner.run();
}
}

View File

@@ -1,11 +1,11 @@
package com.baeldung.objects;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class CarUnitTest {
import static org.junit.Assert.*;
public class ObjectsUnitTest {
private Car car;

View File

@@ -4,3 +4,4 @@
- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java)
- [Java instanceof Operator](https://www.baeldung.com/java-instanceof)
- [A Guide to Increment and Decrement Unary Operators in Java](https://www.baeldung.com/java-unary-operators)
- [Java Compound Operators](https://www.baeldung.com/java-compound-operators)

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