Merge branch 'master' into master
This commit is contained in:
@@ -14,3 +14,4 @@
|
||||
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
|
||||
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
||||
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
|
||||
|
||||
@@ -6,7 +6,6 @@ import static com.datastax.spark.connector.japi.CassandraJavaUtil.mapToRow;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -15,13 +14,7 @@ import org.apache.kafka.common.serialization.StringDeserializer;
|
||||
import org.apache.log4j.Level;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.apache.spark.SparkConf;
|
||||
import org.apache.spark.api.java.JavaPairRDD;
|
||||
import org.apache.spark.api.java.JavaRDD;
|
||||
import org.apache.spark.api.java.function.FlatMapFunction;
|
||||
import org.apache.spark.api.java.function.Function;
|
||||
import org.apache.spark.api.java.function.Function2;
|
||||
import org.apache.spark.api.java.function.PairFunction;
|
||||
import org.apache.spark.api.java.function.VoidFunction;
|
||||
import org.apache.spark.streaming.Durations;
|
||||
import org.apache.spark.streaming.api.java.JavaDStream;
|
||||
import org.apache.spark.streaming.api.java.JavaInputDStream;
|
||||
@@ -35,7 +28,6 @@ import scala.Tuple2;
|
||||
|
||||
public class WordCountingApp {
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
Logger.getLogger("org")
|
||||
.setLevel(Level.OFF);
|
||||
@@ -61,52 +53,24 @@ public class WordCountingApp {
|
||||
|
||||
JavaInputDStream<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies.<String, String> Subscribe(topics, kafkaParams));
|
||||
|
||||
JavaPairDStream<String, String> results = messages.mapToPair(new PairFunction<ConsumerRecord<String, String>, String, String>() {
|
||||
@Override
|
||||
public Tuple2<String, String> call(ConsumerRecord<String, String> record) {
|
||||
return new Tuple2<>(record.key(), record.value());
|
||||
}
|
||||
});
|
||||
JavaPairDStream<String, String> results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value()));
|
||||
|
||||
JavaDStream<String> lines = results.map(new Function<Tuple2<String, String>, String>() {
|
||||
@Override
|
||||
public String call(Tuple2<String, String> tuple2) {
|
||||
return tuple2._2();
|
||||
}
|
||||
});
|
||||
JavaDStream<String> lines = results.map(tuple2 -> tuple2._2());
|
||||
|
||||
JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
|
||||
@Override
|
||||
public Iterator<String> call(String x) {
|
||||
return Arrays.asList(x.split("\\s+"))
|
||||
.iterator();
|
||||
}
|
||||
});
|
||||
JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(x.split("\\s+"))
|
||||
.iterator());
|
||||
|
||||
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(new PairFunction<String, String, Integer>() {
|
||||
@Override
|
||||
public Tuple2<String, Integer> call(String s) {
|
||||
return new Tuple2<>(s, 1);
|
||||
}
|
||||
})
|
||||
.reduceByKey(new Function2<Integer, Integer, Integer>() {
|
||||
@Override
|
||||
public Integer call(Integer i1, Integer i2) {
|
||||
return i1 + i2;
|
||||
}
|
||||
});
|
||||
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
|
||||
.reduceByKey((i1, i2) -> i1 + i2);
|
||||
|
||||
wordCounts.foreachRDD(new VoidFunction<JavaPairRDD<String, Integer>>() {
|
||||
@Override
|
||||
public void call(JavaPairRDD<String, Integer> javaRdd) throws Exception {
|
||||
Map<String, Integer> wordCountMap = javaRdd.collectAsMap();
|
||||
for (String key : wordCountMap.keySet()) {
|
||||
List<Word> words = Arrays.asList(new Word(key, wordCountMap.get(key)));
|
||||
JavaRDD<Word> rdd = streamingContext.sparkContext()
|
||||
.parallelize(words);
|
||||
javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
|
||||
.saveToCassandra();
|
||||
}
|
||||
wordCounts.foreachRDD(javaRdd -> {
|
||||
Map<String, Integer> wordCountMap = javaRdd.collectAsMap();
|
||||
for (String key : wordCountMap.keySet()) {
|
||||
List<Word> wordList = Arrays.asList(new Word(key, wordCountMap.get(key)));
|
||||
JavaRDD<Word> rdd = streamingContext.sparkContext()
|
||||
.parallelize(wordList);
|
||||
javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
|
||||
.saveToCassandra();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+15
-58
@@ -6,7 +6,6 @@ import static com.datastax.spark.connector.japi.CassandraJavaUtil.mapToRow;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -15,18 +14,10 @@ import org.apache.kafka.common.serialization.StringDeserializer;
|
||||
import org.apache.log4j.Level;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.apache.spark.SparkConf;
|
||||
import org.apache.spark.api.java.JavaPairRDD;
|
||||
import org.apache.spark.api.java.JavaRDD;
|
||||
import org.apache.spark.api.java.JavaSparkContext;
|
||||
import org.apache.spark.api.java.Optional;
|
||||
import org.apache.spark.api.java.function.FlatMapFunction;
|
||||
import org.apache.spark.api.java.function.Function;
|
||||
import org.apache.spark.api.java.function.Function2;
|
||||
import org.apache.spark.api.java.function.Function3;
|
||||
import org.apache.spark.api.java.function.PairFunction;
|
||||
import org.apache.spark.api.java.function.VoidFunction;
|
||||
import org.apache.spark.streaming.Durations;
|
||||
import org.apache.spark.streaming.State;
|
||||
import org.apache.spark.streaming.StateSpec;
|
||||
import org.apache.spark.streaming.api.java.JavaDStream;
|
||||
import org.apache.spark.streaming.api.java.JavaInputDStream;
|
||||
@@ -43,7 +34,6 @@ public class WordCountingAppWithCheckpoint {
|
||||
|
||||
public static JavaSparkContext sparkContext;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
|
||||
Logger.getLogger("org")
|
||||
@@ -74,63 +64,30 @@ public class WordCountingAppWithCheckpoint {
|
||||
|
||||
JavaInputDStream<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies.<String, String> Subscribe(topics, kafkaParams));
|
||||
|
||||
JavaPairDStream<String, String> results = messages.mapToPair(new PairFunction<ConsumerRecord<String, String>, String, String>() {
|
||||
@Override
|
||||
public Tuple2<String, String> call(ConsumerRecord<String, String> record) {
|
||||
return new Tuple2<>(record.key(), record.value());
|
||||
}
|
||||
});
|
||||
JavaPairDStream<String, String> results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value()));
|
||||
|
||||
JavaDStream<String> lines = results.map(new Function<Tuple2<String, String>, String>() {
|
||||
@Override
|
||||
public String call(Tuple2<String, String> tuple2) {
|
||||
return tuple2._2();
|
||||
}
|
||||
});
|
||||
JavaDStream<String> lines = results.map(tuple2 -> tuple2._2());
|
||||
|
||||
JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
|
||||
@Override
|
||||
public Iterator<String> call(String x) {
|
||||
return Arrays.asList(x.split("\\s+"))
|
||||
.iterator();
|
||||
}
|
||||
});
|
||||
JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(x.split("\\s+"))
|
||||
.iterator());
|
||||
|
||||
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(new PairFunction<String, String, Integer>() {
|
||||
@Override
|
||||
public Tuple2<String, Integer> call(String s) {
|
||||
return new Tuple2<>(s, 1);
|
||||
}
|
||||
})
|
||||
.reduceByKey(new Function2<Integer, Integer, Integer>() {
|
||||
@Override
|
||||
public Integer call(Integer i1, Integer i2) {
|
||||
return i1 + i2;
|
||||
}
|
||||
});
|
||||
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
|
||||
.reduceByKey((Function2<Integer, Integer, Integer>) (i1, i2) -> i1 + i2);
|
||||
|
||||
Function3<String, Optional<Integer>, State<Integer>, Tuple2<String, Integer>> mappingFunc = (word, one, state) -> {
|
||||
JavaMapWithStateDStream<String, Integer, Integer, Tuple2<String, Integer>> cumulativeWordCounts = wordCounts.mapWithState(StateSpec.function((word, one, state) -> {
|
||||
int sum = one.orElse(0) + (state.exists() ? state.get() : 0);
|
||||
Tuple2<String, Integer> output = new Tuple2<>(word, sum);
|
||||
state.update(sum);
|
||||
return output;
|
||||
};
|
||||
}));
|
||||
|
||||
JavaPairRDD<String, Integer> initialRDD = JavaPairRDD.fromJavaRDD(sparkContext.emptyRDD());
|
||||
|
||||
JavaMapWithStateDStream<String, Integer, Integer, Tuple2<String, Integer>> cumulativeWordCounts = wordCounts.mapWithState(StateSpec.function(mappingFunc)
|
||||
.initialState(initialRDD));
|
||||
|
||||
cumulativeWordCounts.foreachRDD(new VoidFunction<JavaRDD<Tuple2<String, Integer>>>() {
|
||||
@Override
|
||||
public void call(JavaRDD<Tuple2<String, Integer>> javaRdd) throws Exception {
|
||||
List<Tuple2<String, Integer>> wordCountList = javaRdd.collect();
|
||||
for (Tuple2<String, Integer> tuple : wordCountList) {
|
||||
List<Word> words = Arrays.asList(new Word(tuple._1, tuple._2));
|
||||
JavaRDD<Word> rdd = sparkContext.parallelize(words);
|
||||
javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
|
||||
.saveToCassandra();
|
||||
}
|
||||
cumulativeWordCounts.foreachRDD(javaRdd -> {
|
||||
List<Tuple2<String, Integer>> wordCountList = javaRdd.collect();
|
||||
for (Tuple2<String, Integer> tuple : wordCountList) {
|
||||
List<Word> wordList = Arrays.asList(new Word(tuple._1, tuple._2));
|
||||
JavaRDD<Word> rdd = sparkContext.parallelize(wordList);
|
||||
javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
|
||||
.saveToCassandra();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import java.util.Enumeration;
|
||||
import java.util.Iterator;
|
||||
import java.util.Vector;
|
||||
|
||||
public class VectorExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Vector<String> vector = new Vector<>();
|
||||
vector.add("baeldung");
|
||||
vector.add("Vector");
|
||||
vector.add("example");
|
||||
|
||||
Enumeration e = vector.elements();
|
||||
while(e.hasMoreElements()){
|
||||
System.out.println(e.nextElement());
|
||||
}
|
||||
|
||||
Iterator<String> iterator = vector.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
System.out.println(iterator.next());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+19
-6
@@ -9,7 +9,7 @@ import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class ArrayListBenchmark {
|
||||
|
||||
@@ -17,6 +17,7 @@ public class ArrayListBenchmark {
|
||||
public static class MyState {
|
||||
|
||||
List<Employee> employeeList = new ArrayList<>();
|
||||
Vector<Employee> employeeVector = new Vector<>();
|
||||
//LinkedList<Employee> employeeList = new LinkedList<>();
|
||||
|
||||
long iterations = 100000;
|
||||
@@ -29,9 +30,11 @@ public class ArrayListBenchmark {
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeList.add(new Employee(i, "John"));
|
||||
employeeVector.add(new Employee(i, "John"));
|
||||
}
|
||||
|
||||
employeeList.add(employee);
|
||||
employeeVector.add(employee);
|
||||
employeeIndex = employeeList.indexOf(employee);
|
||||
}
|
||||
}
|
||||
@@ -46,6 +49,11 @@ public class ArrayListBenchmark {
|
||||
return state.employeeList.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testContainsVector(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeVector.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int testIndexOf(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.indexOf(state.employee);
|
||||
@@ -56,19 +64,24 @@ public class ArrayListBenchmark {
|
||||
return state.employeeList.get(state.employeeIndex);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testVectorGet(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeVector.get(state.employeeIndex);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testRemove(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.remove(state.employee);
|
||||
}
|
||||
|
||||
// @Benchmark
|
||||
// public void testAdd(ArrayListBenchmark.MyState state) {
|
||||
// state.employeeList.add(new Employee(state.iterations + 1, "John"));
|
||||
// }
|
||||
@Benchmark
|
||||
public void testAdd(ArrayListBenchmark.MyState state) {
|
||||
state.employeeList.add(new Employee(state.iterations + 1, "John"));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(ArrayListBenchmark.class.getSimpleName()).threads(1)
|
||||
.include(ArrayListBenchmark.class.getSimpleName()).threads(3)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.queueinterface;
|
||||
|
||||
import java.util.AbstractQueue;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class CustomBaeldungQueue<T> extends AbstractQueue<T> {
|
||||
|
||||
private LinkedList<T> elements;
|
||||
|
||||
public CustomBaeldungQueue() {
|
||||
this.elements = new LinkedList<T>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<T> iterator() {
|
||||
return elements.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return elements.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean offer(T t) {
|
||||
if(t == null) return false;
|
||||
elements.add(t);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T poll() {
|
||||
|
||||
Iterator<T> iter = elements.iterator();
|
||||
T t = iter.next();
|
||||
if(t != null){
|
||||
iter.remove();
|
||||
return t;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T peek() {
|
||||
return elements.getFirst();
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.queueinterface;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.PriorityQueue;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class PriorityQueueUnitTest {
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void givenIntegerQueue_whenIntegersOutOfOrder_checkRetrievalOrderIsNatural() {
|
||||
|
||||
PriorityQueue<Integer> integerQueue = new PriorityQueue<>();
|
||||
|
||||
integerQueue.add(9);
|
||||
integerQueue.add(2);
|
||||
integerQueue.add(4);
|
||||
|
||||
int first = integerQueue.poll();
|
||||
int second = integerQueue.poll();
|
||||
int third = integerQueue.poll();
|
||||
|
||||
assertEquals(2, first);
|
||||
assertEquals(4, second);
|
||||
assertEquals(9, third);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringQueue_whenStringsAddedOutOfNaturalOrder_checkRetrievalOrderNatural() {
|
||||
|
||||
PriorityQueue<String> stringQueue = new PriorityQueue<>();
|
||||
|
||||
stringQueue.add("banana");
|
||||
stringQueue.add("apple");
|
||||
stringQueue.add("cherry");
|
||||
|
||||
String first = stringQueue.poll();
|
||||
String second = stringQueue.poll();
|
||||
String third = stringQueue.poll();
|
||||
|
||||
assertEquals("apple", first);
|
||||
assertEquals("banana", second);
|
||||
assertEquals("cherry", third);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.queueinterface;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class CustomBaeldungQueueUnitTest {
|
||||
|
||||
private CustomBaeldungQueue<Integer> customQueue;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
customQueue = new CustomBaeldungQueue<>();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenQueueWithTwoElements_whenElementsRetrieved_checkRetrievalCorrect() {
|
||||
|
||||
customQueue.add(7);
|
||||
customQueue.add(5);
|
||||
|
||||
int first = customQueue.poll();
|
||||
int second = customQueue.poll();
|
||||
|
||||
assertEquals(7, first);
|
||||
assertEquals(5, second);
|
||||
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.baeldung.concurrent.threadsafety.application;
|
||||
|
||||
import com.baeldung.concurrent.threadsafety.callables.AtomicCounterCallable;
|
||||
import com.baeldung.concurrent.threadsafety.mathutils.MathUtils;
|
||||
import com.baeldung.concurrent.threadsafety.callables.CounterCallable;
|
||||
import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable;
|
||||
import com.baeldung.concurrent.threadsafety.callables.MessageServiceCallable;
|
||||
import com.baeldung.concurrent.threadsafety.callables.ReentranReadWriteLockCounterCallable;
|
||||
import com.baeldung.concurrent.threadsafety.callables.ReentrantLockCounterCallable;
|
||||
import com.baeldung.concurrent.threadsafety.services.AtomicCounter;
|
||||
import com.baeldung.concurrent.threadsafety.services.Counter;
|
||||
import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter;
|
||||
import com.baeldung.concurrent.threadsafety.services.MessageService;
|
||||
import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter;
|
||||
import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException, ExecutionException {
|
||||
|
||||
new Thread(() -> {
|
||||
System.out.println(MathUtils.factorial(10));
|
||||
}).start();
|
||||
new Thread(() -> {
|
||||
System.out.println(MathUtils.factorial(5));
|
||||
}).start();
|
||||
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(10);
|
||||
MessageService messageService = new MessageService("Welcome to Baeldung!");
|
||||
Future<String> future1 = (Future<String>) executorService.submit(new MessageServiceCallable(messageService));
|
||||
Future<String> future2 = (Future<String>) executorService.submit(new MessageServiceCallable(messageService));
|
||||
System.out.println(future1.get());
|
||||
System.out.println(future2.get());
|
||||
|
||||
Counter counter = new Counter();
|
||||
Future<Integer> future3 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
|
||||
Future<Integer> future4 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
|
||||
System.out.println(future3.get());
|
||||
System.out.println(future4.get());
|
||||
|
||||
ExtrinsicLockCounter extrinsicLockCounter = new ExtrinsicLockCounter();
|
||||
Future<Integer> future5 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter));
|
||||
Future<Integer> future6 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter));
|
||||
System.out.println(future5.get());
|
||||
System.out.println(future6.get());
|
||||
|
||||
ReentrantLockCounter reentrantLockCounter = new ReentrantLockCounter();
|
||||
Future<Integer> future7 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(reentrantLockCounter));
|
||||
Future<Integer> future8 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(reentrantLockCounter));
|
||||
System.out.println(future7.get());
|
||||
System.out.println(future8.get());
|
||||
|
||||
ReentrantReadWriteLockCounter reentrantReadWriteLockCounter = new ReentrantReadWriteLockCounter();
|
||||
Future<Integer> future9 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(reentrantReadWriteLockCounter));
|
||||
Future<Integer> future10 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(reentrantReadWriteLockCounter));
|
||||
System.out.println(future9.get());
|
||||
System.out.println(future10.get());
|
||||
|
||||
AtomicCounter atomicCounter = new AtomicCounter();
|
||||
Future<Integer> future11 = (Future<Integer>) executorService.submit(new AtomicCounterCallable(atomicCounter));
|
||||
Future<Integer> future12 = (Future<Integer>) executorService.submit(new AtomicCounterCallable(atomicCounter));
|
||||
System.out.println(future11.get());
|
||||
System.out.println(future12.get());
|
||||
|
||||
Collection<Integer> syncCollection = Collections.synchronizedCollection(new ArrayList<>());
|
||||
Thread thread11 = new Thread(() -> syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6)));
|
||||
Thread thread12 = new Thread(() -> syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6)));
|
||||
thread11.start();
|
||||
thread12.start();
|
||||
|
||||
Map<String,String> concurrentMap = new ConcurrentHashMap<>();
|
||||
concurrentMap.put("1", "one");
|
||||
concurrentMap.put("2", "two");
|
||||
concurrentMap.put("3", "three");
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.concurrent.threadsafety.callables;
|
||||
|
||||
import com.baeldung.concurrent.threadsafety.services.AtomicCounter;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class AtomicCounterCallable implements Callable<Integer> {
|
||||
|
||||
private final AtomicCounter counter;
|
||||
|
||||
public AtomicCounterCallable(AtomicCounter counter) {
|
||||
this.counter = counter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer call() throws Exception {
|
||||
counter.incrementCounter();
|
||||
return counter.getCounter();
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.concurrent.threadsafety.callables;
|
||||
|
||||
import com.baeldung.concurrent.threadsafety.services.Counter;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class CounterCallable implements Callable<Integer> {
|
||||
|
||||
private final Counter counter;
|
||||
|
||||
public CounterCallable(Counter counter) {
|
||||
this.counter = counter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer call() throws Exception {
|
||||
counter.incrementCounter();
|
||||
return counter.getCounter();
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.concurrent.threadsafety.callables;
|
||||
|
||||
import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class ExtrinsicLockCounterCallable implements Callable<Integer> {
|
||||
|
||||
private final ExtrinsicLockCounter counter;
|
||||
|
||||
public ExtrinsicLockCounterCallable(ExtrinsicLockCounter counter) {
|
||||
this.counter = counter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer call() throws Exception {
|
||||
counter.incrementCounter();
|
||||
return counter.getCounter();
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.concurrent.threadsafety.callables;
|
||||
|
||||
import com.baeldung.concurrent.threadsafety.services.MessageService;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class MessageServiceCallable implements Callable<String> {
|
||||
|
||||
private final MessageService messageService;
|
||||
|
||||
public MessageServiceCallable(MessageService messageService) {
|
||||
this.messageService = messageService;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String call() {
|
||||
return messageService.getMesssage();
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.concurrent.threadsafety.callables;
|
||||
|
||||
import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class ReentranReadWriteLockCounterCallable implements Callable<Integer> {
|
||||
|
||||
private final ReentrantReadWriteLockCounter counter;
|
||||
|
||||
public ReentranReadWriteLockCounterCallable(ReentrantReadWriteLockCounter counter) {
|
||||
this.counter = counter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer call() throws Exception {
|
||||
counter.incrementCounter();
|
||||
return counter.getCounter();
|
||||
}
|
||||
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.concurrent.threadsafety.callables;
|
||||
|
||||
import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class ReentrantLockCounterCallable implements Callable<Integer> {
|
||||
|
||||
private final ReentrantLockCounter counter;
|
||||
|
||||
public ReentrantLockCounterCallable(ReentrantLockCounter counter) {
|
||||
this.counter = counter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer call() throws Exception {
|
||||
counter.incrementCounter();
|
||||
return counter.getCounter();
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.concurrent.threadsafety.mathutils;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class MathUtils {
|
||||
|
||||
public static BigInteger factorial(int number) {
|
||||
BigInteger f = new BigInteger("1");
|
||||
for (int i = 2; i <= number; i++) {
|
||||
f = f.multiply(BigInteger.valueOf(i));
|
||||
}
|
||||
return f;
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.concurrent.threadsafety.services;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class AtomicCounter {
|
||||
|
||||
private final AtomicInteger counter = new AtomicInteger();
|
||||
|
||||
public AtomicCounter() {}
|
||||
|
||||
public void incrementCounter() {
|
||||
counter.incrementAndGet();
|
||||
}
|
||||
|
||||
public synchronized int getCounter() {
|
||||
return counter.get();
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.concurrent.threadsafety.services;
|
||||
|
||||
public class Counter {
|
||||
|
||||
private volatile int counter;
|
||||
|
||||
public Counter() {
|
||||
this.counter = 0;
|
||||
}
|
||||
|
||||
public synchronized void incrementCounter() {
|
||||
counter += 1;
|
||||
}
|
||||
|
||||
public int getCounter() {
|
||||
return counter;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.concurrent.threadsafety.services;
|
||||
|
||||
public class ExtrinsicLockCounter {
|
||||
|
||||
private int counter;
|
||||
private final Object lock = new Object();
|
||||
|
||||
public ExtrinsicLockCounter() {
|
||||
this.counter = 0;
|
||||
}
|
||||
|
||||
public void incrementCounter() {
|
||||
synchronized (lock) {
|
||||
counter += 1;
|
||||
}
|
||||
}
|
||||
|
||||
public int getCounter() {
|
||||
synchronized (lock) {
|
||||
return counter;
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.concurrent.threadsafety.services;
|
||||
|
||||
public class MessageService {
|
||||
|
||||
private final String message;
|
||||
|
||||
public MessageService(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getMesssage() {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.concurrent.threadsafety.services;
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
public class ReentrantLockCounter {
|
||||
|
||||
private int counter;
|
||||
private final ReentrantLock reLock = new ReentrantLock(true);
|
||||
|
||||
public ReentrantLockCounter() {
|
||||
this.counter = 0;
|
||||
}
|
||||
|
||||
public void incrementCounter() {
|
||||
reLock.lock();
|
||||
try {
|
||||
counter += 1;
|
||||
} finally {
|
||||
reLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public int getCounter() {
|
||||
return counter;
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.concurrent.threadsafety.services;
|
||||
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
public class ReentrantReadWriteLockCounter {
|
||||
|
||||
private int counter;
|
||||
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
|
||||
private final Lock readLock = rwLock.readLock();
|
||||
private final Lock writeLock = rwLock.writeLock();
|
||||
|
||||
public ReentrantReadWriteLockCounter() {
|
||||
this.counter = 0;
|
||||
}
|
||||
|
||||
public void incrementCounter() {
|
||||
writeLock.lock();
|
||||
try {
|
||||
counter += 1;
|
||||
} finally {
|
||||
writeLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public int getCounter() {
|
||||
readLock.lock();
|
||||
try {
|
||||
return counter;
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.concurrent.threadsafety.services;
|
||||
|
||||
public class StateHolder {
|
||||
|
||||
private final String state;
|
||||
|
||||
public StateHolder(String state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.concurrent.threadsafety.tests;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import com.baeldung.concurrent.threadsafety.callables.CounterCallable;
|
||||
import com.baeldung.concurrent.threadsafety.services.Counter;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class CounterTest {
|
||||
|
||||
@Test
|
||||
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
Counter counter = new Counter();
|
||||
Future<Integer> future1 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
|
||||
Future<Integer> future2 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
|
||||
|
||||
assertThat(future1.get()).isEqualTo(1);
|
||||
assertThat(future2.get()).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.concurrent.threadsafety.tests;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable;
|
||||
import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class ExtrinsicLockCounterTest {
|
||||
|
||||
@Test
|
||||
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
ExtrinsicLockCounter counter = new ExtrinsicLockCounter();
|
||||
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(counter));
|
||||
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(counter));
|
||||
|
||||
assertThat(future1.get()).isEqualTo(1);
|
||||
assertThat(future2.get()).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.concurrent.threadsafety.tests;
|
||||
|
||||
import com.baeldung.concurrent.threadsafety.mathutils.MathUtils;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class MathUtilsTest {
|
||||
|
||||
@Test
|
||||
public void whenCalledFactorialMethod_thenCorrect() {
|
||||
assertThat(MathUtils.factorial(2)).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.concurrent.threadsafety.tests;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import com.baeldung.concurrent.threadsafety.callables.MessageServiceCallable;
|
||||
import com.baeldung.concurrent.threadsafety.services.MessageService;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class MessageServiceTest {
|
||||
|
||||
@Test
|
||||
public void whenCalledgetMessage_thenCorrect() throws Exception {
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
MessageService messageService = new MessageService("Welcome to Baeldung!");
|
||||
Future<String> future1 = (Future<String>) executorService.submit(new MessageServiceCallable(messageService));
|
||||
Future<String> future2 = (Future<String>) executorService.submit(new MessageServiceCallable(messageService));
|
||||
|
||||
assertThat(future1.get()).isEqualTo("Welcome to Baeldung!");
|
||||
assertThat(future2.get()).isEqualTo("Welcome to Baeldung!");
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.concurrent.threadsafety.tests;
|
||||
|
||||
import com.baeldung.concurrent.threadsafety.callables.ReentrantLockCounterCallable;
|
||||
import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ReentrantLockCounterTest {
|
||||
|
||||
@Test
|
||||
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
ReentrantLockCounter counter = new ReentrantLockCounter();
|
||||
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(counter));
|
||||
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(counter));
|
||||
|
||||
assertThat(future1.get()).isEqualTo(1);
|
||||
assertThat(future2.get()).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.concurrent.threadsafety.tests;
|
||||
|
||||
import com.baeldung.concurrent.threadsafety.callables.ReentranReadWriteLockCounterCallable;
|
||||
import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ReentrantReadWriteLockCounterTest {
|
||||
|
||||
@Test
|
||||
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
ReentrantReadWriteLockCounter counter = new ReentrantReadWriteLockCounter();
|
||||
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
|
||||
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
|
||||
|
||||
assertThat(future1.get()).isEqualTo(1);
|
||||
assertThat(future2.get()).isEqualTo(2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
|
||||
import com.google.common.io.ByteStreams;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class InputStreamToByteBufferUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUsingCoreClasses_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
|
||||
File inputFile = getFile();
|
||||
ByteBuffer bufferByte = ByteBuffer.allocate((int) inputFile.length());
|
||||
FileInputStream in = new FileInputStream(inputFile);
|
||||
in.getChannel().read(bufferByte);
|
||||
|
||||
assertEquals(bufferByte.position(), inputFile.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIo_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
|
||||
File inputFile = getFile();
|
||||
ByteBuffer bufferByte = ByteBuffer.allocateDirect((int) inputFile.length());
|
||||
ReadableByteChannel readableByteChannel = new FileInputStream(inputFile).getChannel();
|
||||
IOUtils.readFully(readableByteChannel, bufferByte);
|
||||
|
||||
assertEquals(bufferByte.position(), inputFile.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
|
||||
File inputFile = getFile();
|
||||
FileInputStream in = new FileInputStream(inputFile);
|
||||
byte[] targetArray = ByteStreams.toByteArray(in);
|
||||
ByteBuffer bufferByte = ByteBuffer.wrap(targetArray);
|
||||
bufferByte.rewind();
|
||||
while (bufferByte.hasRemaining()) {
|
||||
bufferByte.get();
|
||||
}
|
||||
|
||||
assertEquals(bufferByte.position(), inputFile.length());
|
||||
}
|
||||
|
||||
private File getFile() {
|
||||
ClassLoader classLoader = new InputStreamToByteBufferUnitTest().getClass().getClassLoader();
|
||||
|
||||
String fileName = "frontenac-2257154_960_720.jpg";
|
||||
|
||||
return new File(classLoader.getResource(fileName).getFile());
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user