Merge branch 'master' into master
This commit is contained in:
@@ -1,24 +0,0 @@
|
||||
package com.baeldung.concurrent.blockingqueue;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
|
||||
public class BlockingQueueUsage {
|
||||
public static void main(String[] args) {
|
||||
int BOUND = 10;
|
||||
int N_PRODUCERS = 4;
|
||||
int N_CONSUMERS = Runtime.getRuntime().availableProcessors();
|
||||
int poisonPill = Integer.MAX_VALUE;
|
||||
int poisonPillPerProducer = N_CONSUMERS / N_PRODUCERS;
|
||||
|
||||
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(BOUND);
|
||||
|
||||
for (int i = 0; i < N_PRODUCERS; i++) {
|
||||
new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer)).start();
|
||||
}
|
||||
|
||||
for (int j = 0; j < N_CONSUMERS; j++) {
|
||||
new Thread(new NumbersConsumer(queue, poisonPill)).start();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.baeldung.concurrent.blockingqueue;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
|
||||
public class NumbersConsumer implements Runnable {
|
||||
private final BlockingQueue<Integer> queue;
|
||||
private final int poisonPill;
|
||||
|
||||
NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
||||
this.queue = queue;
|
||||
this.poisonPill = poisonPill;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
while (true) {
|
||||
Integer number = queue.take();
|
||||
if (number.equals(poisonPill)) {
|
||||
return;
|
||||
}
|
||||
String result = number.toString();
|
||||
System.out.println(Thread.currentThread().getName() + " result: " + result);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.baeldung.concurrent.blockingqueue;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class NumbersProducer implements Runnable {
|
||||
|
||||
private final BlockingQueue<Integer> numbersQueue;
|
||||
private final int poisonPill;
|
||||
private final int poisonPillPerProducer;
|
||||
|
||||
NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
|
||||
this.numbersQueue = numbersQueue;
|
||||
this.poisonPill = poisonPill;
|
||||
this.poisonPillPerProducer = poisonPillPerProducer;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
generateNumbers();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
private void generateNumbers() throws InterruptedException {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
numbersQueue.put(ThreadLocalRandom.current().nextInt(100));
|
||||
}
|
||||
for (int j = 0; j < poisonPillPerProducer; j++) {
|
||||
numbersQueue.put(poisonPill);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.concurrent.countdownlatch;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
public class BrokenWorker implements Runnable {
|
||||
private final List<String> outputScraper;
|
||||
private final CountDownLatch countDownLatch;
|
||||
|
||||
BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||
this.outputScraper = outputScraper;
|
||||
this.countDownLatch = countDownLatch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (true) {
|
||||
throw new RuntimeException("Oh dear");
|
||||
}
|
||||
countDownLatch.countDown();
|
||||
outputScraper.add("Counted down");
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.baeldung.concurrent.countdownlatch;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
public class WaitingWorker implements Runnable {
|
||||
|
||||
private final List<String> outputScraper;
|
||||
private final CountDownLatch readyThreadCounter;
|
||||
private final CountDownLatch callingThreadBlocker;
|
||||
private final CountDownLatch completedThreadCounter;
|
||||
|
||||
WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
|
||||
|
||||
this.outputScraper = outputScraper;
|
||||
this.readyThreadCounter = readyThreadCounter;
|
||||
this.callingThreadBlocker = callingThreadBlocker;
|
||||
this.completedThreadCounter = completedThreadCounter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// Mark this thread as read / started
|
||||
readyThreadCounter.countDown();
|
||||
try {
|
||||
callingThreadBlocker.await();
|
||||
outputScraper.add("Counted down");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
completedThreadCounter.countDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.concurrent.countdownlatch;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
public class Worker implements Runnable {
|
||||
private final List<String> outputScraper;
|
||||
private final CountDownLatch countDownLatch;
|
||||
|
||||
Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||
this.outputScraper = outputScraper;
|
||||
this.countDownLatch = countDownLatch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// Do some work
|
||||
System.out.println("Doing some logic");
|
||||
outputScraper.add("Counted down");
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package com.baeldung.concurrent.cyclicbarrier;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.BrokenBarrierException;
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
|
||||
public class CyclicBarrierDemo {
|
||||
|
||||
private CyclicBarrier cyclicBarrier;
|
||||
private List<List<Integer>> partialResults = Collections.synchronizedList(new ArrayList<>());
|
||||
private Random random = new Random();
|
||||
private int NUM_PARTIAL_RESULTS;
|
||||
private int NUM_WORKERS;
|
||||
|
||||
|
||||
private void runSimulation(int numWorkers, int numberOfPartialResults) {
|
||||
NUM_PARTIAL_RESULTS = numberOfPartialResults;
|
||||
NUM_WORKERS = numWorkers;
|
||||
|
||||
cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread());
|
||||
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute "
|
||||
+ NUM_PARTIAL_RESULTS + " partial results each");
|
||||
for (int i = 0; i < NUM_WORKERS; i++) {
|
||||
Thread worker = new Thread(new NumberCruncherThread());
|
||||
worker.setName("Thread " + i);
|
||||
worker.start();
|
||||
}
|
||||
}
|
||||
|
||||
class NumberCruncherThread implements Runnable {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
String thisThreadName = Thread.currentThread().getName();
|
||||
List<Integer> partialResult = new ArrayList<>();
|
||||
for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) {
|
||||
Integer num = random.nextInt(10);
|
||||
System.out.println(thisThreadName
|
||||
+ ": Crunching some numbers! Final result - " + num);
|
||||
partialResult.add(num);
|
||||
}
|
||||
partialResults.add(partialResult);
|
||||
try {
|
||||
System.out.println(thisThreadName + " waiting for others to reach barrier.");
|
||||
cyclicBarrier.await();
|
||||
} catch (InterruptedException | BrokenBarrierException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class AggregatorThread implements Runnable {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
String thisThreadName = Thread.currentThread().getName();
|
||||
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS
|
||||
+ " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
|
||||
int sum = 0;
|
||||
for (List<Integer> threadResult : partialResults) {
|
||||
System.out.print("Adding ");
|
||||
for (Integer partialResult : threadResult) {
|
||||
System.out.print(partialResult+" ");
|
||||
sum += partialResult;
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
System.out.println(Thread.currentThread().getName() + ": Final result = " + sum);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
CyclicBarrierDemo play = new CyclicBarrierDemo();
|
||||
play.runSimulation(5, 3);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package com.baeldung.concurrent.delayqueue;
|
||||
|
||||
import com.google.common.primitives.Ints;
|
||||
|
||||
import java.util.concurrent.Delayed;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class DelayObject implements Delayed {
|
||||
private String data;
|
||||
private long startTime;
|
||||
|
||||
DelayObject(String data, long delayInMilliseconds) {
|
||||
this.data = data;
|
||||
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getDelay(TimeUnit unit) {
|
||||
long diff = startTime - System.currentTimeMillis();
|
||||
return unit.convert(diff, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Delayed o) {
|
||||
return Ints.saturatedCast(this.startTime - ((DelayObject) o).startTime);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{" +
|
||||
"data='" + data + '\'' +
|
||||
", startTime=" + startTime +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.baeldung.concurrent.delayqueue;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
|
||||
public class DelayQueueConsumer implements Runnable {
|
||||
private BlockingQueue<DelayObject> queue;
|
||||
private final Integer numberOfElementsToTake;
|
||||
final AtomicInteger numberOfConsumedElements = new AtomicInteger();
|
||||
|
||||
DelayQueueConsumer(BlockingQueue<DelayObject> queue, Integer numberOfElementsToTake) {
|
||||
this.queue = queue;
|
||||
this.numberOfElementsToTake = numberOfElementsToTake;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < numberOfElementsToTake; i++) {
|
||||
try {
|
||||
DelayObject object = queue.take();
|
||||
numberOfConsumedElements.incrementAndGet();
|
||||
System.out.println("Consumer take: " + object);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.baeldung.concurrent.delayqueue;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
|
||||
|
||||
public class DelayQueueProducer implements Runnable {
|
||||
private BlockingQueue<DelayObject> queue;
|
||||
private final Integer numberOfElementsToProduce;
|
||||
private final Integer delayOfEachProducedMessageMilliseconds;
|
||||
|
||||
DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
||||
Integer numberOfElementsToProduce,
|
||||
Integer delayOfEachProducedMessageMilliseconds) {
|
||||
this.queue = queue;
|
||||
this.numberOfElementsToProduce = numberOfElementsToProduce;
|
||||
this.delayOfEachProducedMessageMilliseconds = delayOfEachProducedMessageMilliseconds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < numberOfElementsToProduce; i++) {
|
||||
DelayObject object
|
||||
= new DelayObject(UUID.randomUUID().toString(), delayOfEachProducedMessageMilliseconds);
|
||||
System.out.println("Put object = " + object);
|
||||
try {
|
||||
queue.put(object);
|
||||
Thread.sleep(500);
|
||||
} catch (InterruptedException ie) {
|
||||
ie.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.concurrent.diningphilosophers;
|
||||
|
||||
public class DiningPhilosophers {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
Philosopher[] philosophers = new Philosopher[5];
|
||||
Object[] forks = new Object[philosophers.length];
|
||||
|
||||
for (int i = 0; i < forks.length; i++) {
|
||||
forks[i] = new Object();
|
||||
}
|
||||
|
||||
for (int i = 0; i < philosophers.length; i++) {
|
||||
|
||||
Object leftFork = forks[i];
|
||||
Object rightFork = forks[(i + 1) % forks.length];
|
||||
|
||||
if (i == philosophers.length - 1) {
|
||||
philosophers[i] = new Philosopher(rightFork, leftFork); // The last philosopher picks up the right fork first
|
||||
} else {
|
||||
philosophers[i] = new Philosopher(leftFork, rightFork);
|
||||
}
|
||||
|
||||
Thread t = new Thread(philosophers[i], "Philosopher " + (i + 1));
|
||||
t.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package com.baeldung.concurrent.diningphilosophers;
|
||||
|
||||
public class Philosopher implements Runnable {
|
||||
|
||||
private final Object leftFork;
|
||||
private final Object rightFork;
|
||||
|
||||
Philosopher(Object left, Object right) {
|
||||
this.leftFork = left;
|
||||
this.rightFork = right;
|
||||
}
|
||||
|
||||
private void doAction(String action) throws InterruptedException {
|
||||
System.out.println(Thread.currentThread().getName() + " " + action);
|
||||
Thread.sleep(((int) (Math.random() * 100)));
|
||||
}
|
||||
|
||||
@Override public void run() {
|
||||
try {
|
||||
while (true) {
|
||||
doAction(System.nanoTime() + ": Thinking"); // thinking
|
||||
synchronized (leftFork) {
|
||||
doAction(System.nanoTime() + ": Picked up left fork");
|
||||
synchronized (rightFork) {
|
||||
doAction(System.nanoTime() + ": Picked up right fork - eating"); // eating
|
||||
doAction(System.nanoTime() + ": Put down right fork");
|
||||
}
|
||||
doAction(System.nanoTime() + ": Put down left fork. Returning to thinking");
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.concurrent.future;
|
||||
|
||||
import java.util.concurrent.RecursiveTask;
|
||||
|
||||
public class FactorialSquareCalculator extends RecursiveTask<Integer> {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
final private Integer n;
|
||||
|
||||
FactorialSquareCalculator(Integer n) {
|
||||
this.n = n;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Integer compute() {
|
||||
if (n <= 1) {
|
||||
return n;
|
||||
}
|
||||
|
||||
FactorialSquareCalculator calculator = new FactorialSquareCalculator(n - 1);
|
||||
|
||||
calculator.fork();
|
||||
|
||||
return n * n + calculator.join();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.concurrent.future;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
class SquareCalculator {
|
||||
|
||||
private final ExecutorService executor;
|
||||
|
||||
SquareCalculator(ExecutorService executor) {
|
||||
this.executor = executor;
|
||||
}
|
||||
|
||||
Future<Integer> calculate(Integer input) {
|
||||
return executor.submit(() -> {
|
||||
Thread.sleep(1000);
|
||||
return input * input;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package com.baeldung.concurrent.locks;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Stack;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static java.lang.Thread.sleep;
|
||||
|
||||
public class ReentrantLockWithCondition {
|
||||
|
||||
private static Logger LOG = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
|
||||
|
||||
private Stack<String> stack = new Stack<>();
|
||||
private static final int CAPACITY = 5;
|
||||
|
||||
private ReentrantLock lock = new ReentrantLock();
|
||||
private Condition stackEmptyCondition = lock.newCondition();
|
||||
private Condition stackFullCondition = lock.newCondition();
|
||||
|
||||
private void pushToStack(String item) throws InterruptedException {
|
||||
try {
|
||||
lock.lock();
|
||||
if (stack.size() == CAPACITY) {
|
||||
LOG.info(Thread.currentThread().getName() + " wait on stack full");
|
||||
stackFullCondition.await();
|
||||
}
|
||||
LOG.info("Pushing the item " + item);
|
||||
stack.push(item);
|
||||
stackEmptyCondition.signalAll();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private String popFromStack() throws InterruptedException {
|
||||
try {
|
||||
lock.lock();
|
||||
if (stack.size() == 0) {
|
||||
LOG.info(Thread.currentThread().getName() + " wait on stack empty");
|
||||
stackEmptyCondition.await();
|
||||
}
|
||||
return stack.pop();
|
||||
} finally {
|
||||
stackFullCondition.signalAll();
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
final int threadCount = 2;
|
||||
ReentrantLockWithCondition object = new ReentrantLockWithCondition();
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
service.execute(() -> {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
object.pushToStack("Item " + i);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
service.execute(() -> {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
LOG.info("Item popped " + object.popFromStack());
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
package com.baeldung.concurrent.locks;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static java.lang.Thread.sleep;
|
||||
|
||||
public class SharedObjectWithLock {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SharedObjectWithLock.class);
|
||||
|
||||
private ReentrantLock lock = new ReentrantLock(true);
|
||||
|
||||
private int counter = 0;
|
||||
|
||||
void perform() {
|
||||
|
||||
lock.lock();
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||
try {
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||
counter++;
|
||||
} catch (Exception exception) {
|
||||
LOG.error(" Interrupted Exception ", exception);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||
}
|
||||
}
|
||||
|
||||
private void performTryLock() {
|
||||
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
|
||||
try {
|
||||
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
|
||||
if (isLockAcquired) {
|
||||
try {
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||
sleep(1000);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException exception) {
|
||||
LOG.error(" Interrupted Exception ", exception);
|
||||
}
|
||||
LOG.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
|
||||
}
|
||||
|
||||
public ReentrantLock getLock() {
|
||||
return lock;
|
||||
}
|
||||
|
||||
boolean isLocked() {
|
||||
return lock.isLocked();
|
||||
}
|
||||
|
||||
boolean hasQueuedThreads() {
|
||||
return lock.hasQueuedThreads();
|
||||
}
|
||||
|
||||
int getCounter() {
|
||||
return counter;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
service.execute(object::perform);
|
||||
service.execute(object::performTryLock);
|
||||
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package com.baeldung.concurrent.locks;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.locks.StampedLock;
|
||||
|
||||
import static java.lang.Thread.sleep;
|
||||
|
||||
public class StampedLockDemo {
|
||||
private Map<String, String> map = new HashMap<>();
|
||||
private Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
|
||||
|
||||
private final StampedLock lock = new StampedLock();
|
||||
|
||||
public void put(String key, String value) throws InterruptedException {
|
||||
long stamp = lock.writeLock();
|
||||
|
||||
try {
|
||||
logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp);
|
||||
map.put(key, value);
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp);
|
||||
}
|
||||
}
|
||||
|
||||
public String get(String key) throws InterruptedException {
|
||||
long stamp = lock.readLock();
|
||||
logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp);
|
||||
try {
|
||||
sleep(5000);
|
||||
return map.get(key);
|
||||
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private String readWithOptimisticLock(String key) throws InterruptedException {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
String value = map.get(key);
|
||||
|
||||
if (!lock.validate(stamp)) {
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
sleep(5000);
|
||||
return map.get(key);
|
||||
|
||||
} finally {
|
||||
lock.unlock(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
||||
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
StampedLockDemo object = new StampedLockDemo();
|
||||
|
||||
Runnable writeTask = () -> {
|
||||
|
||||
try {
|
||||
object.put("key1", "value1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
Runnable readTask = () -> {
|
||||
|
||||
try {
|
||||
object.get("key1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
Runnable readOptimisticTask = () -> {
|
||||
|
||||
try {
|
||||
object.readWithOptimisticLock("key1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
service.submit(writeTask);
|
||||
service.submit(writeTask);
|
||||
service.submit(readTask);
|
||||
service.submit(readOptimisticTask);
|
||||
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
package com.baeldung.concurrent.locks;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
import static java.lang.Thread.sleep;
|
||||
|
||||
public class SynchronizedHashMapWithRWLock {
|
||||
|
||||
private static Map<String, String> syncHashMap = new HashMap<>();
|
||||
private Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
|
||||
|
||||
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
private final Lock readLock = lock.readLock();
|
||||
private final Lock writeLock = lock.writeLock();
|
||||
|
||||
public void put(String key, String value) throws InterruptedException {
|
||||
|
||||
try {
|
||||
writeLock.lock();
|
||||
logger.info(Thread.currentThread().getName() + " writing");
|
||||
syncHashMap.put(key, value);
|
||||
sleep(1000);
|
||||
} finally {
|
||||
writeLock.unlock();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String get(String key) {
|
||||
try {
|
||||
readLock.lock();
|
||||
logger.info(Thread.currentThread().getName() + " reading");
|
||||
return syncHashMap.get(key);
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public String remove(String key) {
|
||||
try {
|
||||
writeLock.lock();
|
||||
return syncHashMap.remove(key);
|
||||
} finally {
|
||||
writeLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean containsKey(String key) {
|
||||
try {
|
||||
readLock.lock();
|
||||
return syncHashMap.containsKey(key);
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
boolean isReadLockAvailable() {
|
||||
return readLock.tryLock();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
|
||||
final int threadCount = 3;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
|
||||
service.execute(new Thread(new Writer(object), "Writer"));
|
||||
service.execute(new Thread(new Reader(object), "Reader1"));
|
||||
service.execute(new Thread(new Reader(object), "Reader2"));
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
private static class Reader implements Runnable {
|
||||
|
||||
SynchronizedHashMapWithRWLock object;
|
||||
|
||||
Reader(SynchronizedHashMapWithRWLock object) {
|
||||
this.object = object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
object.get("key" + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class Writer implements Runnable {
|
||||
|
||||
SynchronizedHashMapWithRWLock object;
|
||||
|
||||
public Writer(SynchronizedHashMapWithRWLock object) {
|
||||
this.object = object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
try {
|
||||
object.put("key" + i, "value" + i);
|
||||
sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.concurrent.phaser;
|
||||
|
||||
import java.util.concurrent.Phaser;
|
||||
|
||||
class LongRunningAction implements Runnable {
|
||||
private String threadName;
|
||||
private Phaser ph;
|
||||
|
||||
LongRunningAction(String threadName, Phaser ph) {
|
||||
this.threadName = threadName;
|
||||
this.ph = ph;
|
||||
ph.register();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("This is phase " + ph.getPhase());
|
||||
System.out.println("Thread " + threadName + " before long running action");
|
||||
ph.arriveAndAwaitAdvance();
|
||||
try {
|
||||
Thread.sleep(20);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
ph.arriveAndDeregister();
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.concurrent.semaphores;
|
||||
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
class CounterUsingMutex {
|
||||
|
||||
private final Semaphore mutex;
|
||||
private int count;
|
||||
|
||||
CounterUsingMutex() {
|
||||
mutex = new Semaphore(1);
|
||||
count = 0;
|
||||
}
|
||||
|
||||
void increase() throws InterruptedException {
|
||||
mutex.acquire();
|
||||
this.count = this.count + 1;
|
||||
Thread.sleep(1000);
|
||||
mutex.release();
|
||||
|
||||
}
|
||||
|
||||
int getCount() {
|
||||
return this.count;
|
||||
}
|
||||
|
||||
boolean hasQueuedThreads() {
|
||||
return mutex.hasQueuedThreads();
|
||||
}
|
||||
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.concurrent.semaphores;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.commons.lang3.concurrent.TimedSemaphore;
|
||||
|
||||
class DelayQueueUsingTimedSemaphore {
|
||||
|
||||
private final TimedSemaphore semaphore;
|
||||
|
||||
DelayQueueUsingTimedSemaphore(long period, int slotLimit) {
|
||||
semaphore = new TimedSemaphore(period, TimeUnit.SECONDS, slotLimit);
|
||||
}
|
||||
|
||||
boolean tryAdd() {
|
||||
return semaphore.tryAcquire();
|
||||
}
|
||||
|
||||
int availableSlots() {
|
||||
return semaphore.getAvailablePermits();
|
||||
}
|
||||
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.concurrent.semaphores;
|
||||
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
class LoginQueueUsingSemaphore {
|
||||
|
||||
private final Semaphore semaphore;
|
||||
|
||||
LoginQueueUsingSemaphore(int slotLimit) {
|
||||
semaphore = new Semaphore(slotLimit);
|
||||
}
|
||||
|
||||
boolean tryLogin() {
|
||||
return semaphore.tryAcquire();
|
||||
}
|
||||
|
||||
void logout() {
|
||||
semaphore.release();
|
||||
}
|
||||
|
||||
int availableSlots() {
|
||||
return semaphore.availablePermits();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.baeldung.concurrent.skiplist;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
class Event {
|
||||
private final ZonedDateTime eventTime;
|
||||
private final String content;
|
||||
|
||||
Event(ZonedDateTime eventTime, String content) {
|
||||
this.eventTime = eventTime;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
ZonedDateTime getEventTime() {
|
||||
return eventTime;
|
||||
}
|
||||
|
||||
String getContent() {
|
||||
return content;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.concurrent.skiplist;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Comparator;
|
||||
import java.util.concurrent.ConcurrentNavigableMap;
|
||||
import java.util.concurrent.ConcurrentSkipListMap;
|
||||
|
||||
class EventWindowSort {
|
||||
private final ConcurrentSkipListMap<ZonedDateTime, String> events
|
||||
= new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
|
||||
|
||||
void acceptEvent(Event event) {
|
||||
events.put(event.getEventTime(), event.getContent());
|
||||
}
|
||||
|
||||
ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
|
||||
return events.tailMap(ZonedDateTime
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
}
|
||||
|
||||
ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
||||
return events.headMap(ZonedDateTime
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.concurrent.sleepwait;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/***
|
||||
* Example of waking up a waiting thread
|
||||
*/
|
||||
public class ThreadA {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ThreadA.class);
|
||||
|
||||
private static final ThreadB b = new ThreadB();
|
||||
|
||||
public static void main(String... args) throws InterruptedException {
|
||||
b.start();
|
||||
|
||||
synchronized (b) {
|
||||
while (b.sum == 0) {
|
||||
LOG.debug("Waiting for ThreadB to complete...");
|
||||
b.wait();
|
||||
}
|
||||
|
||||
LOG.debug("ThreadB has completed. Sum from that thread is: " + b.sum);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.concurrent.sleepwait;
|
||||
|
||||
/***
|
||||
* Example of waking up a waiting thread
|
||||
*/
|
||||
class ThreadB extends Thread {
|
||||
int sum;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (this) {
|
||||
int i = 0;
|
||||
while (i < 100000) {
|
||||
sum += i;
|
||||
i++;
|
||||
}
|
||||
notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.concurrent.sleepwait;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/***
|
||||
* Example of wait() and sleep() methods
|
||||
*/
|
||||
public class WaitSleepExample {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WaitSleepExample.class);
|
||||
|
||||
private static final Object LOCK = new Object();
|
||||
|
||||
public static void main(String... args) throws InterruptedException {
|
||||
sleepWaitInSynchronizedBlocks();
|
||||
}
|
||||
|
||||
private static void sleepWaitInSynchronizedBlocks() throws InterruptedException {
|
||||
Thread.sleep(1000); // called on the thread
|
||||
LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
|
||||
|
||||
synchronized (LOCK) {
|
||||
LOCK.wait(1000); // called on the object, synchronization required
|
||||
LOG.debug("Object '" + LOCK + "' is woken after waiting for 1 second");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package com.baeldung.concurrent.synchronize;
|
||||
|
||||
public class BaeldungSynchronizedBlocks {
|
||||
|
||||
private int count = 0;
|
||||
private static int staticCount = 0;
|
||||
|
||||
void performSynchronisedTask() {
|
||||
synchronized (this) {
|
||||
setCount(getCount() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
static void performStaticSyncTask() {
|
||||
synchronized (BaeldungSynchronizedBlocks.class) {
|
||||
setStaticCount(getStaticCount() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
public int getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public void setCount(int count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
static int getStaticCount() {
|
||||
return staticCount;
|
||||
}
|
||||
|
||||
private static void setStaticCount(int staticCount) {
|
||||
BaeldungSynchronizedBlocks.staticCount = staticCount;
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package com.baeldung.concurrent.synchronize;
|
||||
|
||||
public class BaeldungSynchronizedMethods {
|
||||
|
||||
private int sum = 0;
|
||||
private int syncSum = 0;
|
||||
|
||||
static int staticSum = 0;
|
||||
|
||||
void calculate() {
|
||||
setSum(getSum() + 1);
|
||||
}
|
||||
|
||||
synchronized void synchronisedCalculate() {
|
||||
setSyncSum(getSyncSum() + 1);
|
||||
}
|
||||
|
||||
static synchronized void syncStaticCalculate() {
|
||||
staticSum = staticSum + 1;
|
||||
}
|
||||
|
||||
public int getSum() {
|
||||
return sum;
|
||||
}
|
||||
|
||||
public void setSum(int sum) {
|
||||
this.sum = sum;
|
||||
}
|
||||
|
||||
int getSyncSum() {
|
||||
return syncSum;
|
||||
}
|
||||
|
||||
private void setSyncSum(int syncSum) {
|
||||
this.syncSum = syncSum;
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,12 @@ import java.io.Serializable;
|
||||
|
||||
public class AppleProduct implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated)
|
||||
// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated)
|
||||
private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated)
|
||||
// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated)
|
||||
|
||||
public String headphonePort;
|
||||
public String thunderboltPort;
|
||||
public String lighteningPort;
|
||||
public String lightningPort;
|
||||
|
||||
public String getHeadphonePort() {
|
||||
return headphonePort;
|
||||
@@ -23,4 +23,8 @@ public class AppleProduct implements Serializable {
|
||||
return serialVersionUID;
|
||||
}
|
||||
|
||||
public String getLightningPort() {
|
||||
return lightningPort;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -9,11 +9,12 @@ public class DeserializationUtility {
|
||||
|
||||
public static void main(String[] args) throws ClassNotFoundException, IOException {
|
||||
|
||||
String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
|
||||
String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
|
||||
System.out.println("Deserializing AppleProduct...");
|
||||
AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj);
|
||||
System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort());
|
||||
System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort());
|
||||
System.out.println("LightningPort port of AppleProduct:" + deserializedObj.getLightningPort());
|
||||
}
|
||||
|
||||
public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException {
|
||||
|
||||
@@ -13,6 +13,7 @@ public class SerializationUtility {
|
||||
AppleProduct macBook = new AppleProduct();
|
||||
macBook.headphonePort = "headphonePort2020";
|
||||
macBook.thunderboltPort = "thunderboltPort2020";
|
||||
macBook.lightningPort = "lightningPort2020";
|
||||
|
||||
String serializedObj = serializeObjectToString(macBook);
|
||||
System.out.println("Serialized AppleProduct object to string:");
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||
|
||||
public class AdapterPatternDriver {
|
||||
|
||||
public static void main(String args[]) {
|
||||
LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl();
|
||||
LOG.info("Bugatti Veyron Super Sport's top speed is " + luxuryCars.bugattiVeyronInKMPH() + " Kmph.");
|
||||
LOG.info("McLaren F1 top speed is " + luxuryCars.mcLarenInKMPH() + " Kmph.");
|
||||
LOG.info("Aston Martin One-77 top speed is " + luxuryCars.astonMartinInKMPH() + " Kmph.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public class LuxuryCarsSpeed {
|
||||
public double bugattiVeyronInMPH() {
|
||||
return 268;
|
||||
}
|
||||
|
||||
public double mcLarenInMPH() {
|
||||
return 241;
|
||||
}
|
||||
|
||||
public double astonMartinInMPH() {
|
||||
return 220;
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public interface LuxuryCarsSpeedAdapter {
|
||||
public double bugattiVeyronInKMPH();
|
||||
|
||||
public double mcLarenInKMPH();
|
||||
|
||||
public double astonMartinInKMPH();
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public class LuxuryCarsSpeedAdapterImpl extends LuxuryCarsSpeed implements LuxuryCarsSpeedAdapter {
|
||||
|
||||
@Override
|
||||
public double bugattiVeyronInKMPH() {
|
||||
double mph = super.bugattiVeyronInMPH();
|
||||
return convertMPHtoKMPH(mph);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double mcLarenInKMPH() {
|
||||
double mph = super.mcLarenInMPH();
|
||||
return convertMPHtoKMPH(mph);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double astonMartinInKMPH() {
|
||||
double mph = super.astonMartinInMPH();
|
||||
return convertMPHtoKMPH(mph);
|
||||
}
|
||||
|
||||
private double convertMPHtoKMPH(double mph) {
|
||||
return mph * 1.60934;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||
|
||||
public class Blue implements Color {
|
||||
|
||||
@Override
|
||||
public void fillColor() {
|
||||
LOG.info("Color : Blue");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
public class BridgePatternDriver {
|
||||
|
||||
public static void main(String[] args) {
|
||||
//a square with red color
|
||||
Shape square = new Square(new Red());
|
||||
square.drawShape();
|
||||
|
||||
//a triangle with blue color
|
||||
Shape triangle = new Triangle(new Blue());
|
||||
triangle.drawShape();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
public interface Color {
|
||||
public void fillColor();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||
|
||||
public class Red implements Color {
|
||||
|
||||
@Override
|
||||
public void fillColor() {
|
||||
LOG.info("Color : Red");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
public abstract class Shape {
|
||||
protected Color color;
|
||||
|
||||
public Shape(Color color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
abstract public void drawShape();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||
|
||||
public class Square extends Shape {
|
||||
|
||||
public Square(Color color) {
|
||||
super(color);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawShape() {
|
||||
LOG.info("Square drawn. ");
|
||||
color.fillColor();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.designpatterns.bridge;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||
|
||||
public class Triangle extends Shape {
|
||||
|
||||
public Triangle(Color color) {
|
||||
super(color);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawShape() {
|
||||
LOG.info("Triangle drawn. ");
|
||||
color.fillColor();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.designpatterns.decorator;
|
||||
|
||||
public class BubbleLights extends TreeDecorator {
|
||||
|
||||
public BubbleLights(ChristmasTree tree) {
|
||||
super(tree);
|
||||
}
|
||||
|
||||
public String decorate() {
|
||||
return super.decorate() + decorateWithBubbleLights();
|
||||
}
|
||||
|
||||
private String decorateWithBubbleLights() {
|
||||
return " with Bubble Lights";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.designpatterns.decorator;
|
||||
|
||||
public interface ChristmasTree {
|
||||
public String decorate();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.designpatterns.decorator;
|
||||
|
||||
public class ChristmasTreeImpl implements ChristmasTree {
|
||||
|
||||
@Override
|
||||
public String decorate() {
|
||||
return "Christmas tree";
|
||||
}
|
||||
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.designpatterns.decorator;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||
|
||||
public class DecoratorPatternDriver {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// christmas tree with just one Garland
|
||||
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
|
||||
LOG.info(tree1.decorate());
|
||||
|
||||
// christmas tree with two Garlands and one Bubble lights
|
||||
ChristmasTree tree2 = new BubbleLights(new Garland(new Garland(new ChristmasTreeImpl())));
|
||||
LOG.info(tree2.decorate());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.designpatterns.decorator;
|
||||
|
||||
public class Garland extends TreeDecorator {
|
||||
|
||||
public Garland(ChristmasTree tree) {
|
||||
super(tree);
|
||||
}
|
||||
|
||||
public String decorate() {
|
||||
return super.decorate() + decorateWithGarland();
|
||||
}
|
||||
|
||||
private String decorateWithGarland() {
|
||||
return " with Garland";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.designpatterns.decorator;
|
||||
|
||||
public abstract class TreeDecorator implements ChristmasTree {
|
||||
private ChristmasTree tree;
|
||||
|
||||
public TreeDecorator(ChristmasTree tree) {
|
||||
this.tree = tree;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String decorate() {
|
||||
return tree.decorate();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.designpatterns.proxy;
|
||||
|
||||
public interface ExpensiveObject {
|
||||
public void process();
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.designpatterns.proxy;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;;
|
||||
|
||||
public class ExpensiveObjectImpl implements ExpensiveObject {
|
||||
|
||||
public ExpensiveObjectImpl() {
|
||||
heavyInitialConfiguration();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void process() {
|
||||
LOG.info("processing complete.");
|
||||
}
|
||||
|
||||
private void heavyInitialConfiguration() {
|
||||
LOG.info("Loading initial configuration...");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.designpatterns.proxy;
|
||||
|
||||
public class ExpensiveObjectProxy implements ExpensiveObject{
|
||||
private static ExpensiveObject object;
|
||||
|
||||
@Override
|
||||
public void process() {
|
||||
if(object == null) {
|
||||
object = new ExpensiveObjectImpl();
|
||||
}
|
||||
object.process();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.designpatterns.proxy;
|
||||
|
||||
public class ProxyPatternDriver {
|
||||
public static void main(String[] args) {
|
||||
ExpensiveObject object = new ExpensiveObjectProxy();
|
||||
object.process();
|
||||
object.process();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.designpatterns.singleton;
|
||||
|
||||
public class ClassSingleton {
|
||||
|
||||
private static ClassSingleton INSTANCE;
|
||||
private String info = "Initial class info";
|
||||
|
||||
private ClassSingleton(){
|
||||
}
|
||||
|
||||
public static ClassSingleton getInstance(){
|
||||
if(INSTANCE == null){
|
||||
INSTANCE = new ClassSingleton();
|
||||
}
|
||||
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
// getters and setters
|
||||
|
||||
public String getInfo() {
|
||||
return info;
|
||||
}
|
||||
|
||||
public void setInfo(String info) {
|
||||
this.info = info;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.designpatterns.singleton;
|
||||
|
||||
public enum EnumSingleton {
|
||||
|
||||
INSTANCE("Initial enum info"); //Name of the single instance
|
||||
|
||||
private String info;
|
||||
|
||||
private EnumSingleton(String info) {
|
||||
this.info = info;
|
||||
}
|
||||
|
||||
public EnumSingleton getInstance(){
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
//getters and setters
|
||||
|
||||
public String getInfo() {
|
||||
return info;
|
||||
}
|
||||
|
||||
public void setInfo(String info) {
|
||||
this.info = info;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.designpatterns.singleton;
|
||||
|
||||
public class Sandbox {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
//Class singleton
|
||||
|
||||
ClassSingleton classSingleton1 = ClassSingleton.getInstance();
|
||||
//OurSingleton object1 = new OurSingleton(); // The constructor OurSingleton() is not visible
|
||||
|
||||
System.out.println(classSingleton1.getInfo()); //Initial class info
|
||||
|
||||
ClassSingleton classSingleton2 = ClassSingleton.getInstance();
|
||||
classSingleton2.setInfo("New class info");
|
||||
|
||||
System.out.println(classSingleton1.getInfo()); //New class info
|
||||
System.out.println(classSingleton2.getInfo()); //New class info
|
||||
|
||||
//Enum singleton
|
||||
|
||||
EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE.getInstance();
|
||||
|
||||
System.out.println(enumSingleton1.getInfo()); //Initial enum info
|
||||
|
||||
EnumSingleton enumSingleton2 = EnumSingleton.INSTANCE.getInstance();
|
||||
enumSingleton2.setInfo("New enum info");
|
||||
|
||||
System.out.println(enumSingleton1.getInfo()); //New enum info
|
||||
System.out.println(enumSingleton2.getInfo()); //New enum info
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.designpatterns.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.apache.log4j.PropertyConfigurator;
|
||||
|
||||
public class LogerUtil {
|
||||
|
||||
public final static Logger LOG = Logger.getLogger("GLOBAL");
|
||||
|
||||
static {
|
||||
configuration();
|
||||
}
|
||||
|
||||
private static void configuration() {
|
||||
Properties props = new Properties();
|
||||
try {
|
||||
props.load(
|
||||
new BufferedReader(
|
||||
new InputStreamReader(
|
||||
LogerUtil.class.getResourceAsStream("/log4jstructuraldp.properties")
|
||||
)
|
||||
)
|
||||
);
|
||||
} catch (IOException e) {
|
||||
System.out.println("log4jstructuraldp.properties file not configured properly");
|
||||
System.exit(0);
|
||||
}
|
||||
PropertyConfigurator.configure(props);
|
||||
}
|
||||
}
|
||||
@@ -14,26 +14,25 @@ public class LookupFSJNDI {
|
||||
super();
|
||||
init();
|
||||
}
|
||||
|
||||
|
||||
private void init() throws NamingException {
|
||||
Hashtable<String, String> env = new Hashtable<String, String>();
|
||||
|
||||
env.put (Context.INITIAL_CONTEXT_FACTORY,
|
||||
"com.sun.jndi.fscontext.RefFSContextFactory");
|
||||
|
||||
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
|
||||
// URI to namespace (actual directory)
|
||||
env.put(Context.PROVIDER_URL, "file:./src/test/resources");
|
||||
|
||||
|
||||
ctx = new InitialContext(env);
|
||||
}
|
||||
|
||||
public InitialContext getCtx() {
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
public File getFile(String fileName) {
|
||||
File file;
|
||||
try {
|
||||
file = (File)getCtx().lookup(fileName);
|
||||
file = (File) getCtx().lookup(fileName);
|
||||
} catch (NamingException e) {
|
||||
file = null;
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ public class CustomRecursiveAction extends RecursiveAction {
|
||||
|
||||
private void processing(String work) {
|
||||
String result = work.toUpperCase();
|
||||
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName());
|
||||
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread()
|
||||
.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.hashcode.entities;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class User {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(User.class);
|
||||
private long id;
|
||||
private String name;
|
||||
private String email;
|
||||
|
||||
public User(long id, String name, String email) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null)
|
||||
return false;
|
||||
if (this.getClass() != o.getClass())
|
||||
return false;
|
||||
User user = (User) o;
|
||||
return id != user.id && (!name.equals(user.name) && !email.equals(user.email));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = 7;
|
||||
hash = 31 * hash + (int) id;
|
||||
hash = 31 * hash + (name == null ? 0 : name.hashCode());
|
||||
hash = 31 * hash + (email == null ? 0 : email.hashCode());
|
||||
logger.info("hashCode() method called - Computed hash: " + hash);
|
||||
return hash;
|
||||
}
|
||||
// getters and setters here
|
||||
}
|
||||
@@ -5,6 +5,6 @@ import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Greeter {
|
||||
|
||||
public String greet() default "";
|
||||
|
||||
public String greet() default "";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.baeldung.javanetworking.uriurl;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class URIDemo {
|
||||
private final Logger logger = LoggerFactory.getLogger(URIDemo.class);
|
||||
|
||||
String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||
// parsed locator
|
||||
String URISCHEME = "https";
|
||||
String URISCHEMESPECIFIC;
|
||||
String URIHOST = "wordpress.org";
|
||||
String URIAUTHORITY = "wordpress.org:443";
|
||||
|
||||
String URIPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||
int URIPORT = 443;
|
||||
String URIQUERY = "replies=3";
|
||||
String URIFRAGMENT = "post-2278484";
|
||||
String URIUSERINFO;
|
||||
String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT;
|
||||
|
||||
URI uri;
|
||||
URL url;
|
||||
BufferedReader in = null;
|
||||
String URIContent = "";
|
||||
|
||||
private String getParsedPieces(URI uri) {
|
||||
logger.info("*** List of parsed pieces ***");
|
||||
URISCHEME = uri.getScheme();
|
||||
logger.info("URISCHEME: " + URISCHEME);
|
||||
URISCHEMESPECIFIC = uri.getSchemeSpecificPart();
|
||||
logger.info("URISCHEMESPECIFIC: " + URISCHEMESPECIFIC);
|
||||
URIHOST = uri.getHost();
|
||||
URIAUTHORITY = uri.getAuthority();
|
||||
logger.info("URIAUTHORITY: " + URIAUTHORITY);
|
||||
logger.info("URIHOST: " + URIHOST);
|
||||
URIPATH = uri.getPath();
|
||||
logger.info("URIPATH: " + URIPATH);
|
||||
URIPORT = uri.getPort();
|
||||
logger.info("URIPORT: " + URIPORT);
|
||||
URIQUERY = uri.getQuery();
|
||||
logger.info("URIQUERY: " + URIQUERY);
|
||||
URIFRAGMENT = uri.getFragment();
|
||||
logger.info("URIFRAGMENT: " + URIFRAGMENT);
|
||||
|
||||
try {
|
||||
url = uri.toURL();
|
||||
} catch (MalformedURLException e) {
|
||||
logger.info("MalformedURLException thrown: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.info("IllegalArgumentException thrown: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
public String testURIAsNew(String URIString) {
|
||||
// creating URI object
|
||||
try {
|
||||
uri = new URI(URIString);
|
||||
} catch (URISyntaxException e) {
|
||||
logger.info("URISyntaxException thrown: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
return getParsedPieces(uri);
|
||||
}
|
||||
|
||||
public String testURIAsCreate(String URIString) {
|
||||
// creating URI object
|
||||
uri = URI.create(URIString);
|
||||
return getParsedPieces(uri);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
URIDemo demo = new URIDemo();
|
||||
String contentCreate = demo.testURIAsCreate(demo.URICOMPOUND);
|
||||
demo.logger.info(contentCreate);
|
||||
String contentNew = demo.testURIAsNew(demo.URICOMPOUND);
|
||||
demo.logger.info(contentNew);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -1,9 +1,10 @@
|
||||
package com.baeldung.javanetworking.url;
|
||||
package com.baeldung.javanetworking.uriurl;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
@@ -10,7 +10,6 @@ public class JMXTutorialMainlauncher {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class);
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
|
||||
@@ -44,7 +44,8 @@ public class MapIteration {
|
||||
}
|
||||
|
||||
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
|
||||
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
|
||||
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet()
|
||||
.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<String, Integer> pair = iterator.next();
|
||||
System.out.println(pair.getKey() + ":" + pair.getValue());
|
||||
@@ -58,7 +59,9 @@ public class MapIteration {
|
||||
}
|
||||
|
||||
public void iterateUsingStreamAPI(Map<String, Integer> map) {
|
||||
map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
|
||||
map.entrySet()
|
||||
.stream()
|
||||
.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
|
||||
}
|
||||
|
||||
public void iterateKeys(Map<String, Integer> map) {
|
||||
|
||||
@@ -8,7 +8,7 @@ public class BigIntegerImpl {
|
||||
|
||||
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
|
||||
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
|
||||
|
||||
|
||||
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
|
||||
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.networking.cookies;
|
||||
package com.baeldung.networking.cookies;
|
||||
|
||||
import java.net.*;
|
||||
import java.util.List;
|
||||
@@ -9,7 +9,8 @@ public class PersistentCookieStore implements CookieStore, Runnable {
|
||||
public PersistentCookieStore() {
|
||||
store = new CookieManager().getCookieStore();
|
||||
// deserialize cookies into store
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(this));
|
||||
Runtime.getRuntime()
|
||||
.addShutdownHook(new Thread(this));
|
||||
}
|
||||
|
||||
@Override
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.networking.cookies;
|
||||
package com.baeldung.networking.cookies;
|
||||
|
||||
import java.net.*;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.networking.udp;
|
||||
package com.baeldung.networking.udp;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.networking.udp;
|
||||
package com.baeldung.networking.udp;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.networking.udp.broadcast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class BroadcastingClient {
|
||||
private DatagramSocket socket;
|
||||
private InetAddress address;
|
||||
private int expectedServerCount;
|
||||
private byte[] buf;
|
||||
|
||||
public BroadcastingClient(int expectedServerCount) throws Exception {
|
||||
this.expectedServerCount = expectedServerCount;
|
||||
this.address = InetAddress.getByName("255.255.255.255");
|
||||
}
|
||||
|
||||
public int discoverServers(String msg) throws IOException {
|
||||
initializeSocketForBroadcasting();
|
||||
copyMessageOnBuffer(msg);
|
||||
|
||||
// When we want to broadcast not just to local network, call listAllBroadcastAddresses() and execute broadcastPacket for each value.
|
||||
broadcastPacket(address);
|
||||
|
||||
return receivePackets();
|
||||
}
|
||||
|
||||
List<InetAddress> listAllBroadcastAddresses() throws SocketException {
|
||||
List<InetAddress> broadcastList = new ArrayList<>();
|
||||
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
|
||||
while (interfaces.hasMoreElements()) {
|
||||
NetworkInterface networkInterface = interfaces.nextElement();
|
||||
|
||||
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
broadcastList.addAll(networkInterface.getInterfaceAddresses()
|
||||
.stream()
|
||||
.filter(address -> address.getBroadcast() != null)
|
||||
.map(address -> address.getBroadcast())
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
return broadcastList;
|
||||
}
|
||||
|
||||
private void initializeSocketForBroadcasting() throws SocketException {
|
||||
socket = new DatagramSocket();
|
||||
socket.setBroadcast(true);
|
||||
}
|
||||
|
||||
private void copyMessageOnBuffer(String msg) {
|
||||
buf = msg.getBytes();
|
||||
}
|
||||
|
||||
private void broadcastPacket(InetAddress address) throws IOException {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
|
||||
socket.send(packet);
|
||||
}
|
||||
|
||||
private int receivePackets() throws IOException {
|
||||
int serversDiscovered = 0;
|
||||
while (serversDiscovered != expectedServerCount) {
|
||||
receivePacket();
|
||||
serversDiscovered++;
|
||||
}
|
||||
return serversDiscovered;
|
||||
}
|
||||
|
||||
private void receivePacket() throws IOException {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(packet);
|
||||
}
|
||||
|
||||
public void close() {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.networking.udp.broadcast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
|
||||
public class BroadcastingEchoServer extends Thread {
|
||||
|
||||
protected DatagramSocket socket = null;
|
||||
protected boolean running;
|
||||
protected byte[] buf = new byte[256];
|
||||
|
||||
public BroadcastingEchoServer() throws IOException {
|
||||
socket = new DatagramSocket(null);
|
||||
socket.setReuseAddress(true);
|
||||
socket.bind(new InetSocketAddress(4445));
|
||||
}
|
||||
|
||||
public void run() {
|
||||
running = true;
|
||||
|
||||
while (running) {
|
||||
try {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(packet);
|
||||
InetAddress address = packet.getAddress();
|
||||
int port = packet.getPort();
|
||||
packet = new DatagramPacket(buf, buf.length, address, port);
|
||||
String received = new String(packet.getData(), 0, packet.getLength());
|
||||
if (received.equals("end")) {
|
||||
running = false;
|
||||
continue;
|
||||
}
|
||||
socket.send(packet);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
running = false;
|
||||
}
|
||||
}
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.networking.udp.multicast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.MulticastSocket;
|
||||
|
||||
public class MulticastEchoServer extends Thread {
|
||||
|
||||
protected MulticastSocket socket = null;
|
||||
protected byte[] buf = new byte[256];
|
||||
protected InetAddress group = null;
|
||||
|
||||
public MulticastEchoServer() throws IOException {
|
||||
socket = new MulticastSocket(4446);
|
||||
socket.setReuseAddress(true);
|
||||
group = InetAddress.getByName("230.0.0.0");
|
||||
socket.joinGroup(group);
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
while (true) {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(packet);
|
||||
InetAddress address = packet.getAddress();
|
||||
int port = packet.getPort();
|
||||
packet = new DatagramPacket(buf, buf.length, address, port);
|
||||
String received = new String(packet.getData(), 0, packet.getLength());
|
||||
if (received.equals("end")) {
|
||||
break;
|
||||
}
|
||||
socket.send(packet);
|
||||
}
|
||||
socket.leaveGroup(group);
|
||||
socket.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.networking.udp.multicast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
|
||||
public class MulticastingClient {
|
||||
private DatagramSocket socket;
|
||||
private InetAddress group;
|
||||
private int expectedServerCount;
|
||||
private byte[] buf;
|
||||
|
||||
public MulticastingClient(int expectedServerCount) throws Exception {
|
||||
this.expectedServerCount = expectedServerCount;
|
||||
this.socket = new DatagramSocket();
|
||||
this.group = InetAddress.getByName("230.0.0.0");
|
||||
}
|
||||
|
||||
public int discoverServers(String msg) throws IOException {
|
||||
copyMessageOnBuffer(msg);
|
||||
multicastPacket();
|
||||
|
||||
return receivePackets();
|
||||
}
|
||||
|
||||
private void copyMessageOnBuffer(String msg) {
|
||||
buf = msg.getBytes();
|
||||
}
|
||||
|
||||
private void multicastPacket() throws IOException {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446);
|
||||
socket.send(packet);
|
||||
}
|
||||
|
||||
private int receivePackets() throws IOException {
|
||||
int serversDiscovered = 0;
|
||||
while (serversDiscovered != expectedServerCount) {
|
||||
receivePacket();
|
||||
serversDiscovered++;
|
||||
}
|
||||
return serversDiscovered;
|
||||
}
|
||||
|
||||
private void receivePacket() throws IOException {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(packet);
|
||||
}
|
||||
|
||||
public void close() {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.baeldung.numberofdigits;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;;
|
||||
|
||||
public class Benchmarking {;
|
||||
|
||||
private static final int LOWER_BOUND = 1;
|
||||
private static final int UPPER_BOUND = 999999999;
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
LOG.info("Testing all methods...");
|
||||
|
||||
long length = test_stringBasedSolution();
|
||||
LOG.info("String Based Solution : " + length);
|
||||
|
||||
length = test_logarithmicApproach();
|
||||
LOG.info("Logarithmic Approach : " + length);
|
||||
|
||||
length = test_repeatedMultiplication();
|
||||
LOG.info("Repeated Multiplication : " + length);
|
||||
|
||||
length = test_shiftOperators();
|
||||
LOG.info("Shift Operators : " + length);
|
||||
|
||||
length = test_dividingWithPowersOf2();
|
||||
LOG.info("Dividing with Powers of 2 : " + length);
|
||||
|
||||
length = test_divideAndConquer();
|
||||
LOG.info("Divide And Conquer : " + length);
|
||||
|
||||
}
|
||||
|
||||
private static long test_stringBasedSolution() {
|
||||
|
||||
long startTime, stopTime, elapsedTime;
|
||||
startTime = System.currentTimeMillis();
|
||||
|
||||
int total = 0;
|
||||
for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) {
|
||||
total += NumberOfDigits.stringBasedSolution(i);
|
||||
}
|
||||
|
||||
stopTime = System.currentTimeMillis();
|
||||
elapsedTime = stopTime - startTime;
|
||||
|
||||
return elapsedTime;
|
||||
}
|
||||
|
||||
private static long test_logarithmicApproach() {
|
||||
|
||||
long startTime, stopTime, elapsedTime;
|
||||
startTime = System.currentTimeMillis();
|
||||
|
||||
int total = 0;
|
||||
for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) {
|
||||
total += NumberOfDigits.logarithmicApproach(i);
|
||||
}
|
||||
|
||||
stopTime = System.currentTimeMillis();
|
||||
elapsedTime = stopTime - startTime;
|
||||
|
||||
return elapsedTime;
|
||||
}
|
||||
|
||||
private static long test_repeatedMultiplication() {
|
||||
|
||||
long startTime, stopTime, elapsedTime;
|
||||
startTime = System.currentTimeMillis();
|
||||
|
||||
int total = 0;
|
||||
for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) {
|
||||
total += NumberOfDigits.repeatedMultiplication(i);
|
||||
}
|
||||
|
||||
stopTime = System.currentTimeMillis();
|
||||
elapsedTime = stopTime - startTime;
|
||||
|
||||
return elapsedTime;
|
||||
}
|
||||
|
||||
private static long test_shiftOperators() {
|
||||
|
||||
long startTime, stopTime, elapsedTime;
|
||||
startTime = System.currentTimeMillis();
|
||||
|
||||
int total = 0;
|
||||
for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) {
|
||||
total += NumberOfDigits.shiftOperators(i);
|
||||
}
|
||||
|
||||
stopTime = System.currentTimeMillis();
|
||||
elapsedTime = stopTime - startTime;
|
||||
|
||||
return elapsedTime;
|
||||
}
|
||||
|
||||
private static long test_dividingWithPowersOf2() {
|
||||
|
||||
long startTime, stopTime, elapsedTime;
|
||||
startTime = System.currentTimeMillis();
|
||||
|
||||
int total = 0;
|
||||
for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) {
|
||||
total += NumberOfDigits.dividingWithPowersOf2(i);
|
||||
}
|
||||
|
||||
stopTime = System.currentTimeMillis();
|
||||
elapsedTime = stopTime - startTime;
|
||||
|
||||
return elapsedTime;
|
||||
}
|
||||
|
||||
private static long test_divideAndConquer() {
|
||||
|
||||
long startTime, stopTime, elapsedTime;
|
||||
startTime = System.currentTimeMillis();
|
||||
|
||||
int total = 0;
|
||||
for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) {
|
||||
total += NumberOfDigits.divideAndConquer(i);
|
||||
}
|
||||
|
||||
stopTime = System.currentTimeMillis();
|
||||
elapsedTime = stopTime - startTime;
|
||||
|
||||
return elapsedTime;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.baeldung.numberofdigits;
|
||||
|
||||
public class NumberOfDigits {
|
||||
public static int stringBasedSolution(int number) {
|
||||
int length = String.valueOf(number).length();
|
||||
return length;
|
||||
}
|
||||
|
||||
public static int logarithmicApproach(int number) {
|
||||
int length = (int) Math.log10(number) + 1;
|
||||
return length;
|
||||
}
|
||||
|
||||
public static int repeatedMultiplication(int number) {
|
||||
int length = 0;
|
||||
long temp = 1;
|
||||
while(temp <= number) {
|
||||
length++;
|
||||
temp *= 10;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
public static int shiftOperators(int number) {
|
||||
int length = 0;
|
||||
long temp = 1;
|
||||
while(temp <= number) {
|
||||
length++;
|
||||
temp = (temp << 3) + (temp << 1);
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
public static int dividingWithPowersOf2(int number) {
|
||||
int length = 1;
|
||||
if (number >= 100000000) {
|
||||
length += 8;
|
||||
number /= 100000000;
|
||||
}
|
||||
if (number >= 10000) {
|
||||
length += 4;
|
||||
number /= 10000;
|
||||
}
|
||||
if (number >= 100) {
|
||||
length += 2;
|
||||
number /= 100;
|
||||
}
|
||||
if (number >= 10) {
|
||||
length += 1;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
public static int divideAndConquer(int number) {
|
||||
if (number < 100000){
|
||||
// 5 digits or less
|
||||
if (number < 100){
|
||||
// 1 or 2
|
||||
if (number < 10)
|
||||
return 1;
|
||||
else
|
||||
return 2;
|
||||
}else{
|
||||
// 3 to 5 digits
|
||||
if (number < 1000)
|
||||
return 3;
|
||||
else{
|
||||
// 4 or 5 digits
|
||||
if (number < 10000)
|
||||
return 4;
|
||||
else
|
||||
return 5;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 6 digits or more
|
||||
if (number < 10000000) {
|
||||
// 6 or 7 digits
|
||||
if (number < 1000000)
|
||||
return 6;
|
||||
else
|
||||
return 7;
|
||||
} else {
|
||||
// 8 to 10 digits
|
||||
if (number < 100000000)
|
||||
return 8;
|
||||
else {
|
||||
// 9 or 10 digits
|
||||
if (number < 1000000000)
|
||||
return 9;
|
||||
else
|
||||
return 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.numberofdigits;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||
|
||||
public class NumberOfDigitsDriver {
|
||||
public static void main(String[] args) {
|
||||
LOG.info("Testing all methods...");
|
||||
|
||||
long length = NumberOfDigits.stringBasedSolution(602);
|
||||
LOG.info("String Based Solution : " + length);
|
||||
|
||||
length = NumberOfDigits.logarithmicApproach(602);
|
||||
LOG.info("Logarithmic Approach : " + length);
|
||||
|
||||
length = NumberOfDigits.repeatedMultiplication(602);
|
||||
LOG.info("Repeated Multiplication : " + length);
|
||||
|
||||
length = NumberOfDigits.shiftOperators(602);
|
||||
LOG.info("Shift Operators : " + length);
|
||||
|
||||
length = NumberOfDigits.dividingWithPowersOf2(602);
|
||||
LOG.info("Dividing with Powers of 2 : " + length);
|
||||
|
||||
length = NumberOfDigits.divideAndConquer(602);
|
||||
LOG.info("Divide And Conquer : " + length);
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,8 @@ public class Screenshot {
|
||||
}
|
||||
|
||||
public void getScreenshot(int timeToWait) throws Exception {
|
||||
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
|
||||
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit()
|
||||
.getScreenSize());
|
||||
Robot robot = new Robot();
|
||||
BufferedImage img = robot.createScreenCapture(rectangle);
|
||||
ImageIO.write(img, "jpg", new File(path));
|
||||
|
||||
@@ -8,9 +8,8 @@ import java.net.*;
|
||||
|
||||
public class EchoClient {
|
||||
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
|
||||
|
||||
|
||||
private Socket clientSocket;
|
||||
private PrintWriter out;
|
||||
private BufferedReader in;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
@@ -12,15 +12,10 @@ class StringHelper {
|
||||
}
|
||||
|
||||
static String removeLastCharOptional(String s) {
|
||||
return Optional.ofNullable(s)
|
||||
.filter(str -> str.length() != 0)
|
||||
.map(str -> str.substring(0, str.length() - 1))
|
||||
.orElse(s);
|
||||
return Optional.ofNullable(s).filter(str -> str.length() != 0).map(str -> str.substring(0, str.length() - 1)).orElse(s);
|
||||
}
|
||||
|
||||
static String removeLastCharRegexOptional(String s) {
|
||||
return Optional.ofNullable(s)
|
||||
.map(str -> str.replaceAll(".$", ""))
|
||||
.orElse(s);
|
||||
return Optional.ofNullable(s).map(str -> str.replaceAll(".$", "")).orElse(s);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,11 +25,7 @@ public class MyTokenizer {
|
||||
}
|
||||
|
||||
public List<String> getTokensWithCollection(String str) {
|
||||
return Collections
|
||||
.list(new StringTokenizer(str, ","))
|
||||
.stream()
|
||||
.map(token -> (String) token)
|
||||
.collect(Collectors.toList());
|
||||
return Collections.list(new StringTokenizer(str, ",")).stream().map(token -> (String) token).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<String> getTokensFromFile(String path, String delim) {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.temporaladjuster;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.temporal.ChronoField;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.temporal.Temporal;
|
||||
import java.time.temporal.TemporalAdjuster;
|
||||
|
||||
public class CustomTemporalAdjuster implements TemporalAdjuster {
|
||||
|
||||
@Override
|
||||
public Temporal adjustInto(Temporal temporal) {
|
||||
switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) {
|
||||
case FRIDAY:
|
||||
return temporal.plus(3, ChronoUnit.DAYS);
|
||||
case SATURDAY:
|
||||
return temporal.plus(2, ChronoUnit.DAYS);
|
||||
default:
|
||||
return temporal.plus(1, ChronoUnit.DAYS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.baeldung.threadlocal;
|
||||
|
||||
|
||||
public class Context {
|
||||
private final String userName;
|
||||
|
||||
public Context(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Context{" +
|
||||
"userNameSecret='" + userName + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.baeldung.threadlocal;
|
||||
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class SharedMapWithUserContext implements Runnable {
|
||||
public final static Map<Integer, Context> userContextPerUserId = new ConcurrentHashMap<>();
|
||||
private final Integer userId;
|
||||
private UserRepository userRepository = new UserRepository();
|
||||
|
||||
public SharedMapWithUserContext(Integer userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
String userName = userRepository.getUserNameForUserId(userId);
|
||||
userContextPerUserId.put(userId, new Context(userName));
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.baeldung.threadlocal;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class ThreadLocalWithUserContext implements Runnable {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalWithUserContext.class);
|
||||
|
||||
private static final ThreadLocal<Context> userContext = new ThreadLocal<>();
|
||||
private final Integer userId;
|
||||
private UserRepository userRepository = new UserRepository();
|
||||
|
||||
public ThreadLocalWithUserContext(Integer userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
String userName = userRepository.getUserNameForUserId(userId);
|
||||
userContext.set(new Context(userName));
|
||||
LOG.debug("thread context for given userId: " + userId + " is: " + userContext.get());
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.threadlocal;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
|
||||
public class UserRepository {
|
||||
public String getUserNameForUserId(Integer userId) {
|
||||
return UUID.randomUUID().toString();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.threadpool;
|
||||
|
||||
import java.util.concurrent.ForkJoinTask;
|
||||
import java.util.concurrent.RecursiveTask;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class CountingTask extends RecursiveTask<Integer> {
|
||||
|
||||
private final TreeNode node;
|
||||
|
||||
public CountingTask(TreeNode node) {
|
||||
this.node = node;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Integer compute() {
|
||||
return node.value + node.children.stream().map(childNode -> new CountingTask(childNode).fork()).collect(Collectors.summingInt(ForkJoinTask::join));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.threadpool;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.google.common.util.concurrent.MoreExecutors;
|
||||
|
||||
/**
|
||||
* This class demonstrates the usage of Guava's exiting executor services that keep the VM from hanging.
|
||||
* Without the exiting executor service, the task would hang indefinitely.
|
||||
* This behaviour cannot be demonstrated in JUnit tests, as JUnit kills the VM after the tests.
|
||||
*/
|
||||
public class ExitingExecutorServiceExample {
|
||||
|
||||
public static void main(String... args) {
|
||||
|
||||
final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
|
||||
final ExecutorService executorService = MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);
|
||||
|
||||
executorService.submit((Runnable) () -> {
|
||||
while (true) {
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.threadpool;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
public class TreeNode {
|
||||
|
||||
int value;
|
||||
|
||||
Set<TreeNode> children;
|
||||
|
||||
public TreeNode(int value, TreeNode... children) {
|
||||
this.value = value;
|
||||
this.children = Sets.newHashSet(children);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.transferqueue;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.TransferQueue;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class Consumer implements Runnable {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
|
||||
|
||||
|
||||
private final TransferQueue<String> transferQueue;
|
||||
private final String name;
|
||||
private final int numberOfMessagesToConsume;
|
||||
public final AtomicInteger numberOfConsumedMessages = new AtomicInteger();
|
||||
|
||||
public Consumer(TransferQueue<String> transferQueue, String name, int numberOfMessagesToConsume) {
|
||||
this.transferQueue = transferQueue;
|
||||
this.name = name;
|
||||
this.numberOfMessagesToConsume = numberOfMessagesToConsume;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < numberOfMessagesToConsume; i++) {
|
||||
try {
|
||||
LOG.debug("Consumer: " + name + " is waiting to take element...");
|
||||
String element = transferQueue.take();
|
||||
longProcessing(element);
|
||||
LOG.debug("Consumer: " + name + " received element: " + element);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void longProcessing(String element) throws InterruptedException {
|
||||
numberOfConsumedMessages.incrementAndGet();
|
||||
Thread.sleep(500);
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.transferqueue;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TransferQueue;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class Producer implements Runnable {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(Producer.class);
|
||||
|
||||
private final TransferQueue<String> transferQueue;
|
||||
private final String name;
|
||||
private final Integer numberOfMessagesToProduce;
|
||||
public final AtomicInteger numberOfProducedMessages = new AtomicInteger();
|
||||
|
||||
public Producer(TransferQueue<String> transferQueue, String name, Integer numberOfMessagesToProduce) {
|
||||
this.transferQueue = transferQueue;
|
||||
this.name = name;
|
||||
this.numberOfMessagesToProduce = numberOfMessagesToProduce;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < numberOfMessagesToProduce; i++) {
|
||||
try {
|
||||
LOG.debug("Producer: " + name + " is waiting to transfer...");
|
||||
boolean added = transferQueue.tryTransfer("A" + i, 4000, TimeUnit.MILLISECONDS);
|
||||
if (added) {
|
||||
numberOfProducedMessages.incrementAndGet();
|
||||
LOG.debug("Producer: " + name + " transferred element: A" + i);
|
||||
} else {
|
||||
LOG.debug("can not add an element due to the timeout");
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,16 +6,16 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.util.UUID;
|
||||
|
||||
public class UUIDGenerator {
|
||||
|
||||
|
||||
/**
|
||||
* These are predefined UUID for name spaces
|
||||
*/
|
||||
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8";
|
||||
|
||||
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
|
||||
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
@@ -35,7 +35,7 @@ public class UUIDGenerator {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
return uuid;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Type 3 UUID Generation
|
||||
*
|
||||
@@ -47,7 +47,7 @@ public class UUIDGenerator {
|
||||
UUID uuid = UUID.nameUUIDFromBytes(bytes);
|
||||
return uuid;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Type 5 UUID Generation
|
||||
*
|
||||
@@ -59,8 +59,7 @@ public class UUIDGenerator {
|
||||
UUID uuid = type5UUIDFromBytes(bytes);
|
||||
return uuid;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static UUID type5UUIDFromBytes(byte[] name) {
|
||||
MessageDigest md;
|
||||
try {
|
||||
@@ -69,27 +68,26 @@ public class UUIDGenerator {
|
||||
throw new InternalError("MD5 not supported", nsae);
|
||||
}
|
||||
byte[] bytes = md.digest(name);
|
||||
bytes[6] &= 0x0f; /* clear version */
|
||||
bytes[6] |= 0x50; /* set to version 5 */
|
||||
bytes[8] &= 0x3f; /* clear variant */
|
||||
bytes[8] |= 0x80; /* set to IETF variant */
|
||||
bytes[6] &= 0x0f; /* clear version */
|
||||
bytes[6] |= 0x50; /* set to version 5 */
|
||||
bytes[8] &= 0x3f; /* clear variant */
|
||||
bytes[8] |= 0x80; /* set to IETF variant */
|
||||
return constructType5UUID(bytes);
|
||||
}
|
||||
|
||||
|
||||
private static UUID constructType5UUID(byte[] data) {
|
||||
long msb = 0;
|
||||
long lsb = 0;
|
||||
assert data.length == 16 : "data must be 16 bytes in length";
|
||||
|
||||
for (int i=0; i<8; i++)
|
||||
|
||||
for (int i = 0; i < 8; i++)
|
||||
msb = (msb << 8) | (data[i] & 0xff);
|
||||
|
||||
for (int i=8; i<16; i++)
|
||||
|
||||
for (int i = 8; i < 16; i++)
|
||||
lsb = (lsb << 8) | (data[i] & 0xff);
|
||||
return new UUID(msb, lsb);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Unique Keys Generation Using Message Digest and Type 4 UUID
|
||||
*
|
||||
|
||||
@@ -4,7 +4,7 @@ public class Rectangle extends Shape {
|
||||
private double width;
|
||||
private double length;
|
||||
|
||||
public Rectangle(double width, double length) {
|
||||
Rectangle(double width, double length) {
|
||||
this.width = width;
|
||||
this.length = length;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
package org.baeldung.executable;
|
||||
|
||||
import javax.swing.JOptionPane;
|
||||
import javax.swing.*;
|
||||
|
||||
public class ExecutableMavenJar {
|
||||
|
||||
public static void main(String[] args) {
|
||||
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
|
||||
# Root logger
|
||||
log4j.rootLogger=INFO, file, stdout
|
||||
|
||||
# Write to console
|
||||
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.stdout.Target=System.out
|
||||
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class DateDiffUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoDatesBeforeJava8_whenDifferentiating_thenWeGetSix() throws ParseException {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
|
||||
Date firstDate = sdf.parse("06/24/2017");
|
||||
Date secondDate = sdf.parse("06/30/2017");
|
||||
|
||||
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
|
||||
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
|
||||
LocalDate now = LocalDate.now();
|
||||
LocalDate sixDaysBehind = now.minusDays(6);
|
||||
|
||||
Duration duration = Duration.between(now, sixDaysBehind);
|
||||
long diff = Math.abs(duration.toDays());
|
||||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDateTimesInJava8_whenDifferentiating_thenWeGetSix() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime sixMinutesBehind = now.minusMinutes(6);
|
||||
|
||||
Duration duration = Duration.between(now, sixMinutesBehind);
|
||||
long diff = Math.abs(duration.toMinutes());
|
||||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() {
|
||||
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
|
||||
org.joda.time.LocalDate sixDaysBehind = now.minusDays(6);
|
||||
|
||||
org.joda.time.Period period = new org.joda.time.Period(now, sixDaysBehind);
|
||||
long diff = Math.abs(period.getDays());
|
||||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDateTimesInJodaTime_whenDifferentiating_thenWeGetSix() {
|
||||
org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now();
|
||||
org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6);
|
||||
|
||||
org.joda.time.Period period = new org.joda.time.Period(now, sixMinutesBehind);
|
||||
long diff = Math.abs(period.getDays());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoDatesInDate4j_whenDifferentiating_thenWeGetSix() {
|
||||
hirondelle.date4j.DateTime now = hirondelle.date4j.DateTime.now(TimeZone.getDefault());
|
||||
hirondelle.date4j.DateTime sixDaysBehind = now.minusDays(6);
|
||||
|
||||
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
|
||||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
}
|
||||
-177
@@ -1,177 +0,0 @@
|
||||
package com.baeldung.completablefuture;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CompletableFutureLongRunningUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class);
|
||||
|
||||
|
||||
@Test
|
||||
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
|
||||
Future<String> completableFuture = calculateAsync();
|
||||
|
||||
String result = completableFuture.get();
|
||||
assertEquals("Hello", result);
|
||||
}
|
||||
|
||||
private Future<String> calculateAsync() throws InterruptedException {
|
||||
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||
|
||||
Executors.newCachedThreadPool().submit(() -> {
|
||||
Thread.sleep(500);
|
||||
completableFuture.complete("Hello");
|
||||
return null;
|
||||
});
|
||||
|
||||
return completableFuture;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException {
|
||||
Future<String> completableFuture = CompletableFuture.completedFuture("Hello");
|
||||
|
||||
String result = completableFuture.get();
|
||||
assertEquals("Hello", result);
|
||||
}
|
||||
|
||||
private Future<String> calculateAsyncWithCancellation() throws InterruptedException {
|
||||
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||
|
||||
Executors.newCachedThreadPool().submit(() -> {
|
||||
Thread.sleep(500);
|
||||
completableFuture.cancel(false);
|
||||
return null;
|
||||
});
|
||||
|
||||
return completableFuture;
|
||||
}
|
||||
|
||||
@Test(expected = CancellationException.class)
|
||||
public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException {
|
||||
Future<String> future = calculateAsyncWithCancellation();
|
||||
future.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");
|
||||
|
||||
assertEquals("Hello", future.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||
|
||||
CompletableFuture<Void> future = completableFuture.thenAccept(s -> LOG.debug("Computation returned: " + s));
|
||||
|
||||
future.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||
|
||||
CompletableFuture<Void> future = completableFuture.thenRun(() -> LOG.debug("Computation finished."));
|
||||
|
||||
future.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||
|
||||
CompletableFuture<String> future = completableFuture.thenApply(s -> s + " World");
|
||||
|
||||
assertEquals("Hello World", future.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
|
||||
|
||||
assertEquals("Hello World", completableFuture.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2);
|
||||
|
||||
assertEquals("Hello World", completableFuture.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
|
||||
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Beautiful");
|
||||
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "World");
|
||||
|
||||
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2, future3);
|
||||
|
||||
// ...
|
||||
|
||||
combinedFuture.get();
|
||||
|
||||
assertTrue(future1.isDone());
|
||||
assertTrue(future2.isDone());
|
||||
assertTrue(future3.isDone());
|
||||
|
||||
String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" "));
|
||||
|
||||
assertEquals("Hello Beautiful World", combined);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException {
|
||||
String name = null;
|
||||
|
||||
// ...
|
||||
|
||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
|
||||
if (name == null) {
|
||||
throw new RuntimeException("Computation error!");
|
||||
}
|
||||
return "Hello, " + name;
|
||||
}).handle((s, t) -> s != null ? s : "Hello, Stranger!");
|
||||
|
||||
assertEquals("Hello, Stranger!", completableFuture.get());
|
||||
}
|
||||
|
||||
@Test(expected = ExecutionException.class)
|
||||
public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||
|
||||
// ...
|
||||
|
||||
completableFuture.completeExceptionally(new RuntimeException("Calculation failed!"));
|
||||
|
||||
// ...
|
||||
|
||||
completableFuture.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||
|
||||
CompletableFuture<String> future = completableFuture.thenApplyAsync(s -> s + " World");
|
||||
|
||||
assertEquals("Hello World", future.get());
|
||||
}
|
||||
|
||||
}
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.concurrent.accumulator;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.LongAccumulator;
|
||||
import java.util.function.LongBinaryOperator;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class LongAccumulatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException {
|
||||
//given
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(8);
|
||||
LongBinaryOperator sum = Long::sum;
|
||||
LongAccumulator accumulator = new LongAccumulator(sum, 0L);
|
||||
int numberOfThreads = 4;
|
||||
int numberOfIncrements = 100;
|
||||
|
||||
//when
|
||||
Runnable accumulateAction = () -> IntStream
|
||||
.rangeClosed(0, numberOfIncrements)
|
||||
.forEach(accumulator::accumulate);
|
||||
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
executorService.execute(accumulateAction);
|
||||
}
|
||||
|
||||
|
||||
//then
|
||||
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
|
||||
executorService.shutdown();
|
||||
assertEquals(accumulator.get(), 20200);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user