parent
6e994240f7
commit
ef34fc6576
@ -6,7 +6,7 @@ public class NumbersConsumer implements Runnable {
|
|||||||
private final BlockingQueue<Integer> queue;
|
private final BlockingQueue<Integer> queue;
|
||||||
private final int poisonPill;
|
private final int poisonPill;
|
||||||
|
|
||||||
public NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
||||||
this.queue = queue;
|
this.queue = queue;
|
||||||
this.poisonPill = poisonPill;
|
this.poisonPill = poisonPill;
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,7 @@ public class NumbersProducer implements Runnable {
|
|||||||
private final int poisonPill;
|
private final int poisonPill;
|
||||||
private final int poisonPillPerProducer;
|
private final int poisonPillPerProducer;
|
||||||
|
|
||||||
public NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
|
NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
|
||||||
this.numbersQueue = numbersQueue;
|
this.numbersQueue = numbersQueue;
|
||||||
this.poisonPill = poisonPill;
|
this.poisonPill = poisonPill;
|
||||||
this.poisonPillPerProducer = poisonPillPerProducer;
|
this.poisonPillPerProducer = poisonPillPerProducer;
|
||||||
|
@ -7,7 +7,7 @@ public class BrokenWorker implements Runnable {
|
|||||||
private final List<String> outputScraper;
|
private final List<String> outputScraper;
|
||||||
private final CountDownLatch countDownLatch;
|
private final CountDownLatch countDownLatch;
|
||||||
|
|
||||||
public BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||||
this.outputScraper = outputScraper;
|
this.outputScraper = outputScraper;
|
||||||
this.countDownLatch = countDownLatch;
|
this.countDownLatch = countDownLatch;
|
||||||
}
|
}
|
||||||
|
@ -10,7 +10,7 @@ public class WaitingWorker implements Runnable {
|
|||||||
private final CountDownLatch callingThreadBlocker;
|
private final CountDownLatch callingThreadBlocker;
|
||||||
private final CountDownLatch completedThreadCounter;
|
private final CountDownLatch completedThreadCounter;
|
||||||
|
|
||||||
public WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
|
WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
|
||||||
|
|
||||||
this.outputScraper = outputScraper;
|
this.outputScraper = outputScraper;
|
||||||
this.readyThreadCounter = readyThreadCounter;
|
this.readyThreadCounter = readyThreadCounter;
|
||||||
|
@ -7,7 +7,7 @@ public class Worker implements Runnable {
|
|||||||
private final List<String> outputScraper;
|
private final List<String> outputScraper;
|
||||||
private final CountDownLatch countDownLatch;
|
private final CountDownLatch countDownLatch;
|
||||||
|
|
||||||
public Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||||
this.outputScraper = outputScraper;
|
this.outputScraper = outputScraper;
|
||||||
this.countDownLatch = countDownLatch;
|
this.countDownLatch = countDownLatch;
|
||||||
}
|
}
|
||||||
|
@ -7,9 +7,6 @@ import java.util.Random;
|
|||||||
import java.util.concurrent.BrokenBarrierException;
|
import java.util.concurrent.BrokenBarrierException;
|
||||||
import java.util.concurrent.CyclicBarrier;
|
import java.util.concurrent.CyclicBarrier;
|
||||||
|
|
||||||
/**
|
|
||||||
* Created by cv on 24/6/17.
|
|
||||||
*/
|
|
||||||
public class CyclicBarrierDemo {
|
public class CyclicBarrierDemo {
|
||||||
|
|
||||||
private CyclicBarrier cyclicBarrier;
|
private CyclicBarrier cyclicBarrier;
|
||||||
@ -19,7 +16,7 @@ public class CyclicBarrierDemo {
|
|||||||
private int NUM_WORKERS;
|
private int NUM_WORKERS;
|
||||||
|
|
||||||
|
|
||||||
public void runSimulation(int numWorkers, int numberOfPartialResults) {
|
private void runSimulation(int numWorkers, int numberOfPartialResults) {
|
||||||
NUM_PARTIAL_RESULTS = numberOfPartialResults;
|
NUM_PARTIAL_RESULTS = numberOfPartialResults;
|
||||||
NUM_WORKERS = numWorkers;
|
NUM_WORKERS = numWorkers;
|
||||||
|
|
||||||
@ -49,9 +46,7 @@ public class CyclicBarrierDemo {
|
|||||||
try {
|
try {
|
||||||
System.out.println(thisThreadName + " waiting for others to reach barrier.");
|
System.out.println(thisThreadName + " waiting for others to reach barrier.");
|
||||||
cyclicBarrier.await();
|
cyclicBarrier.await();
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException | BrokenBarrierException e) {
|
||||||
e.printStackTrace();
|
|
||||||
} catch (BrokenBarrierException e) {
|
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,7 @@ public class DelayObject implements Delayed {
|
|||||||
private String data;
|
private String data;
|
||||||
private long startTime;
|
private long startTime;
|
||||||
|
|
||||||
public DelayObject(String data, long delayInMilliseconds) {
|
DelayObject(String data, long delayInMilliseconds) {
|
||||||
this.data = data;
|
this.data = data;
|
||||||
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
|
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
|
||||||
}
|
}
|
||||||
|
@ -7,9 +7,9 @@ import java.util.concurrent.atomic.AtomicInteger;
|
|||||||
public class DelayQueueConsumer implements Runnable {
|
public class DelayQueueConsumer implements Runnable {
|
||||||
private BlockingQueue<DelayObject> queue;
|
private BlockingQueue<DelayObject> queue;
|
||||||
private final Integer numberOfElementsToTake;
|
private final Integer numberOfElementsToTake;
|
||||||
public final AtomicInteger numberOfConsumedElements = new AtomicInteger();
|
final AtomicInteger numberOfConsumedElements = new AtomicInteger();
|
||||||
|
|
||||||
public DelayQueueConsumer(BlockingQueue<DelayObject> queue, Integer numberOfElementsToTake) {
|
DelayQueueConsumer(BlockingQueue<DelayObject> queue, Integer numberOfElementsToTake) {
|
||||||
this.queue = queue;
|
this.queue = queue;
|
||||||
this.numberOfElementsToTake = numberOfElementsToTake;
|
this.numberOfElementsToTake = numberOfElementsToTake;
|
||||||
}
|
}
|
||||||
|
@ -9,9 +9,9 @@ public class DelayQueueProducer implements Runnable {
|
|||||||
private final Integer numberOfElementsToProduce;
|
private final Integer numberOfElementsToProduce;
|
||||||
private final Integer delayOfEachProducedMessageMilliseconds;
|
private final Integer delayOfEachProducedMessageMilliseconds;
|
||||||
|
|
||||||
public DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
||||||
Integer numberOfElementsToProduce,
|
Integer numberOfElementsToProduce,
|
||||||
Integer delayOfEachProducedMessageMilliseconds) {
|
Integer delayOfEachProducedMessageMilliseconds) {
|
||||||
this.queue = queue;
|
this.queue = queue;
|
||||||
this.numberOfElementsToProduce = numberOfElementsToProduce;
|
this.numberOfElementsToProduce = numberOfElementsToProduce;
|
||||||
this.delayOfEachProducedMessageMilliseconds = delayOfEachProducedMessageMilliseconds;
|
this.delayOfEachProducedMessageMilliseconds = delayOfEachProducedMessageMilliseconds;
|
||||||
|
@ -5,7 +5,7 @@ public class Philosopher implements Runnable {
|
|||||||
private final Object leftFork;
|
private final Object leftFork;
|
||||||
private final Object rightFork;
|
private final Object rightFork;
|
||||||
|
|
||||||
public Philosopher(Object left, Object right) {
|
Philosopher(Object left, Object right) {
|
||||||
this.leftFork = left;
|
this.leftFork = left;
|
||||||
this.rightFork = right;
|
this.rightFork = right;
|
||||||
}
|
}
|
||||||
@ -30,7 +30,6 @@ public class Philosopher implements Runnable {
|
|||||||
}
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -7,7 +7,7 @@ public class FactorialSquareCalculator extends RecursiveTask<Integer> {
|
|||||||
|
|
||||||
final private Integer n;
|
final private Integer n;
|
||||||
|
|
||||||
public FactorialSquareCalculator(Integer n) {
|
FactorialSquareCalculator(Integer n) {
|
||||||
this.n = n;
|
this.n = n;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,15 +3,15 @@ package com.baeldung.concurrent.future;
|
|||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Future;
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
public class SquareCalculator {
|
class SquareCalculator {
|
||||||
|
|
||||||
private final ExecutorService executor;
|
private final ExecutorService executor;
|
||||||
|
|
||||||
public SquareCalculator(ExecutorService executor) {
|
SquareCalculator(ExecutorService executor) {
|
||||||
this.executor = executor;
|
this.executor = executor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Future<Integer> calculate(Integer input) {
|
Future<Integer> calculate(Integer input) {
|
||||||
return executor.submit(() -> {
|
return executor.submit(() -> {
|
||||||
Thread.sleep(1000);
|
Thread.sleep(1000);
|
||||||
return input * input;
|
return input * input;
|
||||||
|
@ -13,71 +13,71 @@ import static java.lang.Thread.sleep;
|
|||||||
|
|
||||||
public class ReentrantLockWithCondition {
|
public class ReentrantLockWithCondition {
|
||||||
|
|
||||||
static Logger logger = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
|
private static Logger LOG = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
|
||||||
|
|
||||||
Stack<String> stack = new Stack<>();
|
private Stack<String> stack = new Stack<>();
|
||||||
int CAPACITY = 5;
|
private static final int CAPACITY = 5;
|
||||||
|
|
||||||
ReentrantLock lock = new ReentrantLock();
|
private ReentrantLock lock = new ReentrantLock();
|
||||||
Condition stackEmptyCondition = lock.newCondition();
|
private Condition stackEmptyCondition = lock.newCondition();
|
||||||
Condition stackFullCondition = lock.newCondition();
|
private Condition stackFullCondition = lock.newCondition();
|
||||||
|
|
||||||
public void pushToStack(String item) throws InterruptedException {
|
private void pushToStack(String item) throws InterruptedException {
|
||||||
try {
|
try {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
if (stack.size() == CAPACITY) {
|
if (stack.size() == CAPACITY) {
|
||||||
logger.info(Thread.currentThread().getName() + " wait on stack full");
|
LOG.info(Thread.currentThread().getName() + " wait on stack full");
|
||||||
stackFullCondition.await();
|
stackFullCondition.await();
|
||||||
}
|
}
|
||||||
logger.info("Pushing the item " + item);
|
LOG.info("Pushing the item " + item);
|
||||||
stack.push(item);
|
stack.push(item);
|
||||||
stackEmptyCondition.signalAll();
|
stackEmptyCondition.signalAll();
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String popFromStack() throws InterruptedException {
|
private String popFromStack() throws InterruptedException {
|
||||||
try {
|
try {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
if (stack.size() == 0) {
|
if (stack.size() == 0) {
|
||||||
logger.info(Thread.currentThread().getName() + " wait on stack empty");
|
LOG.info(Thread.currentThread().getName() + " wait on stack empty");
|
||||||
stackEmptyCondition.await();
|
stackEmptyCondition.await();
|
||||||
}
|
}
|
||||||
return stack.pop();
|
return stack.pop();
|
||||||
} finally {
|
} finally {
|
||||||
stackFullCondition.signalAll();
|
stackFullCondition.signalAll();
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
final int threadCount = 2;
|
final int threadCount = 2;
|
||||||
ReentrantLockWithCondition object = new ReentrantLockWithCondition();
|
ReentrantLockWithCondition object = new ReentrantLockWithCondition();
|
||||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||||
service.execute(() -> {
|
service.execute(() -> {
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
try {
|
try {
|
||||||
object.pushToStack("Item " + i);
|
object.pushToStack("Item " + i);
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
service.execute(() -> {
|
service.execute(() -> {
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
try {
|
try {
|
||||||
logger.info("Item popped " + object.popFromStack());
|
LOG.info("Item popped " + object.popFromStack());
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
service.shutdown();
|
service.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -12,81 +12,77 @@ import static java.lang.Thread.sleep;
|
|||||||
|
|
||||||
public class SharedObjectWithLock {
|
public class SharedObjectWithLock {
|
||||||
|
|
||||||
Logger logger = LoggerFactory.getLogger(SharedObjectWithLock.class);
|
private static final Logger LOG = LoggerFactory.getLogger(SharedObjectWithLock.class);
|
||||||
|
|
||||||
ReentrantLock lock = new ReentrantLock(true);
|
private ReentrantLock lock = new ReentrantLock(true);
|
||||||
|
|
||||||
int counter = 0;
|
private int counter = 0;
|
||||||
|
|
||||||
public void perform() {
|
void perform() {
|
||||||
|
|
||||||
lock.lock();
|
lock.lock();
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||||
try {
|
try {
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||||
counter++;
|
counter++;
|
||||||
} catch (Exception exception) {
|
} catch (Exception exception) {
|
||||||
logger.error(" Interrupted Exception ", exception);
|
LOG.error(" Interrupted Exception ", exception);
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void performTryLock() {
|
private void performTryLock() {
|
||||||
|
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
|
||||||
try {
|
try {
|
||||||
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
|
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
|
||||||
if (isLockAcquired) {
|
if (isLockAcquired) {
|
||||||
try {
|
try {
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||||
|
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||||
sleep(1000);
|
sleep(1000);
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (InterruptedException exception) {
|
} catch (InterruptedException exception) {
|
||||||
logger.error(" Interrupted Exception ", exception);
|
LOG.error(" Interrupted Exception ", exception);
|
||||||
}
|
}
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
|
||||||
}
|
}
|
||||||
|
|
||||||
public ReentrantLock getLock() {
|
public ReentrantLock getLock() {
|
||||||
return lock;
|
return lock;
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean isLocked() {
|
boolean isLocked() {
|
||||||
return lock.isLocked();
|
return lock.isLocked();
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean hasQueuedThreads() {
|
boolean hasQueuedThreads() {
|
||||||
return lock.hasQueuedThreads();
|
return lock.hasQueuedThreads();
|
||||||
}
|
}
|
||||||
|
|
||||||
int getCounter() {
|
int getCounter() {
|
||||||
return counter;
|
return counter;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|
||||||
final int threadCount = 2;
|
final int threadCount = 2;
|
||||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||||
|
|
||||||
service.execute(() -> {
|
service.execute(object::perform);
|
||||||
object.perform();
|
service.execute(object::performTryLock);
|
||||||
});
|
|
||||||
service.execute(() -> {
|
|
||||||
object.performTryLock();
|
|
||||||
});
|
|
||||||
|
|
||||||
service.shutdown();
|
service.shutdown();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -12,93 +12,93 @@ import java.util.concurrent.locks.StampedLock;
|
|||||||
import static java.lang.Thread.sleep;
|
import static java.lang.Thread.sleep;
|
||||||
|
|
||||||
public class StampedLockDemo {
|
public class StampedLockDemo {
|
||||||
Map<String, String> map = new HashMap<>();
|
private Map<String, String> map = new HashMap<>();
|
||||||
Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
|
private Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
|
||||||
|
|
||||||
private final StampedLock lock = new StampedLock();
|
private final StampedLock lock = new StampedLock();
|
||||||
|
|
||||||
public void put(String key, String value) throws InterruptedException {
|
public void put(String key, String value) throws InterruptedException {
|
||||||
long stamp = lock.writeLock();
|
long stamp = lock.writeLock();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp);
|
logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp);
|
||||||
map.put(key, value);
|
map.put(key, value);
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlockWrite(stamp);
|
lock.unlockWrite(stamp);
|
||||||
logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp);
|
logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String get(String key) throws InterruptedException {
|
public String get(String key) throws InterruptedException {
|
||||||
long stamp = lock.readLock();
|
long stamp = lock.readLock();
|
||||||
logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp);
|
logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp);
|
||||||
try {
|
try {
|
||||||
sleep(5000);
|
sleep(5000);
|
||||||
return map.get(key);
|
return map.get(key);
|
||||||
|
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlockRead(stamp);
|
lock.unlockRead(stamp);
|
||||||
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String readWithOptimisticLock(String key) throws InterruptedException {
|
private String readWithOptimisticLock(String key) throws InterruptedException {
|
||||||
long stamp = lock.tryOptimisticRead();
|
long stamp = lock.tryOptimisticRead();
|
||||||
String value = map.get(key);
|
String value = map.get(key);
|
||||||
|
|
||||||
if (!lock.validate(stamp)) {
|
if (!lock.validate(stamp)) {
|
||||||
stamp = lock.readLock();
|
stamp = lock.readLock();
|
||||||
try {
|
try {
|
||||||
sleep(5000);
|
sleep(5000);
|
||||||
return map.get(key);
|
return map.get(key);
|
||||||
|
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock(stamp);
|
lock.unlock(stamp);
|
||||||
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
final int threadCount = 4;
|
final int threadCount = 4;
|
||||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||||
StampedLockDemo object = new StampedLockDemo();
|
StampedLockDemo object = new StampedLockDemo();
|
||||||
|
|
||||||
Runnable writeTask = () -> {
|
Runnable writeTask = () -> {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
object.put("key1", "value1");
|
object.put("key1", "value1");
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Runnable readTask = () -> {
|
Runnable readTask = () -> {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
object.get("key1");
|
object.get("key1");
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Runnable readOptimisticTask = () -> {
|
Runnable readOptimisticTask = () -> {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
object.readWithOptimisticLock("key1");
|
object.readWithOptimisticLock("key1");
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
service.submit(writeTask);
|
service.submit(writeTask);
|
||||||
service.submit(writeTask);
|
service.submit(writeTask);
|
||||||
service.submit(readTask);
|
service.submit(readTask);
|
||||||
service.submit(readOptimisticTask);
|
service.submit(readOptimisticTask);
|
||||||
|
|
||||||
service.shutdown();
|
service.shutdown();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -15,106 +15,106 @@ import static java.lang.Thread.sleep;
|
|||||||
|
|
||||||
public class SynchronizedHashMapWithRWLock {
|
public class SynchronizedHashMapWithRWLock {
|
||||||
|
|
||||||
static Map<String, String> syncHashMap = new HashMap<>();
|
private static Map<String, String> syncHashMap = new HashMap<>();
|
||||||
Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
|
private Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
|
||||||
|
|
||||||
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||||
private final Lock readLock = lock.readLock();
|
private final Lock readLock = lock.readLock();
|
||||||
private final Lock writeLock = lock.writeLock();
|
private final Lock writeLock = lock.writeLock();
|
||||||
|
|
||||||
public void put(String key, String value) throws InterruptedException {
|
public void put(String key, String value) throws InterruptedException {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeLock.lock();
|
writeLock.lock();
|
||||||
logger.info(Thread.currentThread().getName() + " writing");
|
logger.info(Thread.currentThread().getName() + " writing");
|
||||||
syncHashMap.put(key, value);
|
syncHashMap.put(key, value);
|
||||||
sleep(1000);
|
sleep(1000);
|
||||||
} finally {
|
} finally {
|
||||||
writeLock.unlock();
|
writeLock.unlock();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String get(String key) {
|
public String get(String key) {
|
||||||
try {
|
try {
|
||||||
readLock.lock();
|
readLock.lock();
|
||||||
logger.info(Thread.currentThread().getName() + " reading");
|
logger.info(Thread.currentThread().getName() + " reading");
|
||||||
return syncHashMap.get(key);
|
return syncHashMap.get(key);
|
||||||
} finally {
|
} finally {
|
||||||
readLock.unlock();
|
readLock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String remove(String key) {
|
public String remove(String key) {
|
||||||
try {
|
try {
|
||||||
writeLock.lock();
|
writeLock.lock();
|
||||||
return syncHashMap.remove(key);
|
return syncHashMap.remove(key);
|
||||||
} finally {
|
} finally {
|
||||||
writeLock.unlock();
|
writeLock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean containsKey(String key) {
|
public boolean containsKey(String key) {
|
||||||
try {
|
try {
|
||||||
readLock.lock();
|
readLock.lock();
|
||||||
return syncHashMap.containsKey(key);
|
return syncHashMap.containsKey(key);
|
||||||
} finally {
|
} finally {
|
||||||
readLock.unlock();
|
readLock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean isReadLockAvailable() {
|
boolean isReadLockAvailable() {
|
||||||
return readLock.tryLock();
|
return readLock.tryLock();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) throws InterruptedException {
|
public static void main(String[] args) throws InterruptedException {
|
||||||
|
|
||||||
final int threadCount = 3;
|
final int threadCount = 3;
|
||||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||||
|
|
||||||
service.execute(new Thread(new Writer(object), "Writer"));
|
service.execute(new Thread(new Writer(object), "Writer"));
|
||||||
service.execute(new Thread(new Reader(object), "Reader1"));
|
service.execute(new Thread(new Reader(object), "Reader1"));
|
||||||
service.execute(new Thread(new Reader(object), "Reader2"));
|
service.execute(new Thread(new Reader(object), "Reader2"));
|
||||||
|
|
||||||
service.shutdown();
|
service.shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class Reader implements Runnable {
|
private static class Reader implements Runnable {
|
||||||
|
|
||||||
SynchronizedHashMapWithRWLock object;
|
SynchronizedHashMapWithRWLock object;
|
||||||
|
|
||||||
public Reader(SynchronizedHashMapWithRWLock object) {
|
Reader(SynchronizedHashMapWithRWLock object) {
|
||||||
this.object = object;
|
this.object = object;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
object.get("key" + i);
|
object.get("key" + i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class Writer implements Runnable {
|
private static class Writer implements Runnable {
|
||||||
|
|
||||||
SynchronizedHashMapWithRWLock object;
|
SynchronizedHashMapWithRWLock object;
|
||||||
|
|
||||||
public Writer(SynchronizedHashMapWithRWLock object) {
|
public Writer(SynchronizedHashMapWithRWLock object) {
|
||||||
this.object = object;
|
this.object = object;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
try {
|
try {
|
||||||
object.put("key" + i, "value" + i);
|
object.put("key" + i, "value" + i);
|
||||||
sleep(1000);
|
sleep(1000);
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -2,20 +2,20 @@ package com.baeldung.concurrent.skiplist;
|
|||||||
|
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
|
||||||
public class Event {
|
class Event {
|
||||||
private final ZonedDateTime eventTime;
|
private final ZonedDateTime eventTime;
|
||||||
private final String content;
|
private final String content;
|
||||||
|
|
||||||
public Event(ZonedDateTime eventTime, String content) {
|
Event(ZonedDateTime eventTime, String content) {
|
||||||
this.eventTime = eventTime;
|
this.eventTime = eventTime;
|
||||||
this.content = content;
|
this.content = content;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ZonedDateTime getEventTime() {
|
ZonedDateTime getEventTime() {
|
||||||
return eventTime;
|
return eventTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getContent() {
|
String getContent() {
|
||||||
return content;
|
return content;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,24 +5,24 @@ import java.util.Comparator;
|
|||||||
import java.util.concurrent.ConcurrentNavigableMap;
|
import java.util.concurrent.ConcurrentNavigableMap;
|
||||||
import java.util.concurrent.ConcurrentSkipListMap;
|
import java.util.concurrent.ConcurrentSkipListMap;
|
||||||
|
|
||||||
public class EventWindowSort {
|
class EventWindowSort {
|
||||||
private final ConcurrentSkipListMap<ZonedDateTime, String> events
|
private final ConcurrentSkipListMap<ZonedDateTime, String> events
|
||||||
= new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
|
= new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
|
||||||
|
|
||||||
public void acceptEvent(Event event) {
|
void acceptEvent(Event event) {
|
||||||
events.put(event.getEventTime(), event.getContent());
|
events.put(event.getEventTime(), event.getContent());
|
||||||
}
|
}
|
||||||
|
|
||||||
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
|
ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
|
||||||
return events.tailMap(ZonedDateTime
|
return events.tailMap(ZonedDateTime
|
||||||
.now()
|
.now()
|
||||||
.minusMinutes(1));
|
.minusMinutes(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
||||||
return events.headMap(ZonedDateTime
|
return events.headMap(ZonedDateTime
|
||||||
.now()
|
.now()
|
||||||
.minusMinutes(1));
|
.minusMinutes(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -13,10 +13,10 @@ public class WaitSleepExample {
|
|||||||
private static final Object LOCK = new Object();
|
private static final Object LOCK = new Object();
|
||||||
|
|
||||||
public static void main(String... args) throws InterruptedException {
|
public static void main(String... args) throws InterruptedException {
|
||||||
sleepWaitInSyncronizedBlocks();
|
sleepWaitInSynchronizedBlocks();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void sleepWaitInSyncronizedBlocks() throws InterruptedException {
|
private static void sleepWaitInSynchronizedBlocks() throws InterruptedException {
|
||||||
Thread.sleep(1000); // called on the thread
|
Thread.sleep(1000); // called on the thread
|
||||||
LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
|
LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
|
||||||
|
|
||||||
@ -25,5 +25,5 @@ public class WaitSleepExample {
|
|||||||
LOG.debug("Object '" + LOCK + "' is woken after waiting for 1 second");
|
LOG.debug("Object '" + LOCK + "' is woken after waiting for 1 second");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -5,13 +5,13 @@ public class BaeldungSynchronizedBlocks {
|
|||||||
private int count = 0;
|
private int count = 0;
|
||||||
private static int staticCount = 0;
|
private static int staticCount = 0;
|
||||||
|
|
||||||
public void performSynchronisedTask() {
|
void performSynchronisedTask() {
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
setCount(getCount() + 1);
|
setCount(getCount() + 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void performStaticSyncTask() {
|
static void performStaticSyncTask() {
|
||||||
synchronized (BaeldungSynchronizedBlocks.class) {
|
synchronized (BaeldungSynchronizedBlocks.class) {
|
||||||
setStaticCount(getStaticCount() + 1);
|
setStaticCount(getStaticCount() + 1);
|
||||||
}
|
}
|
||||||
@ -25,11 +25,11 @@ public class BaeldungSynchronizedBlocks {
|
|||||||
this.count = count;
|
this.count = count;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static int getStaticCount() {
|
static int getStaticCount() {
|
||||||
return staticCount;
|
return staticCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void setStaticCount(int staticCount) {
|
private static void setStaticCount(int staticCount) {
|
||||||
BaeldungSynchronizedBlocks.staticCount = staticCount;
|
BaeldungSynchronizedBlocks.staticCount = staticCount;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,17 +5,17 @@ public class BaeldungSynchronizedMethods {
|
|||||||
private int sum = 0;
|
private int sum = 0;
|
||||||
private int syncSum = 0;
|
private int syncSum = 0;
|
||||||
|
|
||||||
public static int staticSum = 0;
|
static int staticSum = 0;
|
||||||
|
|
||||||
public void calculate() {
|
void calculate() {
|
||||||
setSum(getSum() + 1);
|
setSum(getSum() + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void synchronisedCalculate() {
|
synchronized void synchronisedCalculate() {
|
||||||
setSyncSum(getSyncSum() + 1);
|
setSyncSum(getSyncSum() + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static synchronized void syncStaticCalculate() {
|
static synchronized void syncStaticCalculate() {
|
||||||
staticSum = staticSum + 1;
|
staticSum = staticSum + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -27,11 +27,11 @@ public class BaeldungSynchronizedMethods {
|
|||||||
this.sum = sum;
|
this.sum = sum;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getSyncSum() {
|
int getSyncSum() {
|
||||||
return syncSum;
|
return syncSum;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setSyncSum(int syncSum) {
|
private void setSyncSum(int syncSum) {
|
||||||
this.syncSum = syncSum;
|
this.syncSum = syncSum;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,40 +6,40 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
||||||
import java.time.temporal.TemporalAdjusters;
|
import java.time.temporal.TemporalAdjusters;
|
||||||
|
|
||||||
public class UseLocalDate {
|
class UseLocalDate {
|
||||||
|
|
||||||
public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
|
LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
|
||||||
return LocalDate.of(year, month, dayOfMonth);
|
return LocalDate.of(year, month, dayOfMonth);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getLocalDateUsingParseMethod(String representation) {
|
LocalDate getLocalDateUsingParseMethod(String representation) {
|
||||||
return LocalDate.parse(representation);
|
return LocalDate.parse(representation);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getLocalDateFromClock() {
|
LocalDate getLocalDateFromClock() {
|
||||||
LocalDate localDate = LocalDate.now();
|
LocalDate localDate = LocalDate.now();
|
||||||
return localDate;
|
return localDate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getNextDay(LocalDate localDate) {
|
LocalDate getNextDay(LocalDate localDate) {
|
||||||
return localDate.plusDays(1);
|
return localDate.plusDays(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getPreviousDay(LocalDate localDate) {
|
LocalDate getPreviousDay(LocalDate localDate) {
|
||||||
return localDate.minus(1, ChronoUnit.DAYS);
|
return localDate.minus(1, ChronoUnit.DAYS);
|
||||||
}
|
}
|
||||||
|
|
||||||
public DayOfWeek getDayOfWeek(LocalDate localDate) {
|
DayOfWeek getDayOfWeek(LocalDate localDate) {
|
||||||
DayOfWeek day = localDate.getDayOfWeek();
|
DayOfWeek day = localDate.getDayOfWeek();
|
||||||
return day;
|
return day;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getFirstDayOfMonth() {
|
LocalDate getFirstDayOfMonth() {
|
||||||
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
||||||
return firstDayOfMonth;
|
return firstDayOfMonth;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDateTime getStartOfDay(LocalDate localDate) {
|
LocalDateTime getStartOfDay(LocalDate localDate) {
|
||||||
LocalDateTime startofDay = localDate.atStartOfDay();
|
LocalDateTime startofDay = localDate.atStartOfDay();
|
||||||
return startofDay;
|
return startofDay;
|
||||||
}
|
}
|
||||||
|
@ -5,31 +5,27 @@ import java.time.temporal.ChronoUnit;
|
|||||||
|
|
||||||
public class UseLocalTime {
|
public class UseLocalTime {
|
||||||
|
|
||||||
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
||||||
LocalTime localTime = LocalTime.of(hour, min, seconds);
|
return LocalTime.of(hour, min, seconds);
|
||||||
return localTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
||||||
LocalTime localTime = LocalTime.parse(timeRepresentation);
|
return LocalTime.parse(timeRepresentation);
|
||||||
return localTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeFromClock() {
|
private LocalTime getLocalTimeFromClock() {
|
||||||
LocalTime localTime = LocalTime.now();
|
return LocalTime.now();
|
||||||
return localTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime addAnHour(LocalTime localTime) {
|
LocalTime addAnHour(LocalTime localTime) {
|
||||||
LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS);
|
return localTime.plus(1, ChronoUnit.HOURS);
|
||||||
return newTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getHourFromLocalTime(LocalTime localTime) {
|
int getHourFromLocalTime(LocalTime localTime) {
|
||||||
return localTime.getHour();
|
return localTime.getHour();
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
||||||
return localTime.withMinute(minute);
|
return localTime.withMinute(minute);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,13 +3,13 @@ package com.baeldung.datetime;
|
|||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.Period;
|
import java.time.Period;
|
||||||
|
|
||||||
public class UsePeriod {
|
class UsePeriod {
|
||||||
|
|
||||||
public LocalDate modifyDates(LocalDate localDate, Period period) {
|
LocalDate modifyDates(LocalDate localDate, Period period) {
|
||||||
return localDate.plus(period);
|
return localDate.plus(period);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
||||||
return Period.between(localDate1, localDate2);
|
return Period.between(localDate1, localDate2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,12 +8,10 @@ import java.util.Date;
|
|||||||
public class UseToInstant {
|
public class UseToInstant {
|
||||||
|
|
||||||
public LocalDateTime convertDateToLocalDate(Date date) {
|
public LocalDateTime convertDateToLocalDate(Date date) {
|
||||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||||
return localDateTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
|
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
|
||||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||||
return localDateTime;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,10 +4,9 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
|
||||||
public class UseZonedDateTime {
|
class UseZonedDateTime {
|
||||||
|
|
||||||
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
||||||
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
|
return ZonedDateTime.of(localDateTime, zoneId);
|
||||||
return zonedDateTime;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -13,8 +13,7 @@ public class DirectoryMonitoringExample {
|
|||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
|
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
|
||||||
|
|
||||||
|
private static final int POLL_INTERVAL = 500;
|
||||||
public static final int POLL_INTERVAL = 500;
|
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
|
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
|
||||||
|
@ -6,12 +6,12 @@ public class Computer {
|
|||||||
private String color;
|
private String color;
|
||||||
private Integer healty;
|
private Integer healty;
|
||||||
|
|
||||||
public Computer(final int age, final String color) {
|
Computer(final int age, final String color) {
|
||||||
this.age = age;
|
this.age = age;
|
||||||
this.color = color;
|
this.color = color;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Computer(final Integer age, final String color, final Integer healty) {
|
Computer(final Integer age, final String color, final Integer healty) {
|
||||||
this.age = age;
|
this.age = age;
|
||||||
this.color = color;
|
this.color = color;
|
||||||
this.healty = healty;
|
this.healty = healty;
|
||||||
@ -28,7 +28,7 @@ public class Computer {
|
|||||||
this.age = age;
|
this.age = age;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getColor() {
|
String getColor() {
|
||||||
return color;
|
return color;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,11 +36,11 @@ public class Computer {
|
|||||||
this.color = color;
|
this.color = color;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Integer getHealty() {
|
Integer getHealty() {
|
||||||
return healty;
|
return healty;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setHealty(final Integer healty) {
|
void setHealty(final Integer healty) {
|
||||||
this.healty = healty;
|
this.healty = healty;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -72,10 +72,7 @@ public class Computer {
|
|||||||
|
|
||||||
final Computer computer = (Computer) o;
|
final Computer computer = (Computer) o;
|
||||||
|
|
||||||
if (age != null ? !age.equals(computer.age) : computer.age != null) {
|
return (age != null ? age.equals(computer.age) : computer.age == null) && (color != null ? color.equals(computer.color) : computer.color == null);
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return color != null ? color.equals(computer.color) : computer.color == null;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -7,8 +7,8 @@ import java.util.List;
|
|||||||
|
|
||||||
public class ComputerUtils {
|
public class ComputerUtils {
|
||||||
|
|
||||||
public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
||||||
public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
||||||
|
|
||||||
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
||||||
|
|
||||||
@ -18,7 +18,7 @@ public class ComputerUtils {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void repair(final Computer computer) {
|
static void repair(final Computer computer) {
|
||||||
if (computer.getHealty() < 50) {
|
if (computer.getHealty() < 50) {
|
||||||
computer.setHealty(100);
|
computer.setHealty(100);
|
||||||
}
|
}
|
||||||
|
@ -13,7 +13,7 @@ public class MacbookPro extends Computer {
|
|||||||
super(age, color);
|
super(age, color);
|
||||||
}
|
}
|
||||||
|
|
||||||
public MacbookPro(Integer age, String color, Integer healty) {
|
MacbookPro(Integer age, String color, Integer healty) {
|
||||||
super(age, color, healty);
|
super(age, color, healty);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -15,7 +15,7 @@ public class TimingDynamicInvocationHandler implements InvocationHandler {
|
|||||||
|
|
||||||
private Object target;
|
private Object target;
|
||||||
|
|
||||||
public TimingDynamicInvocationHandler(Object target) {
|
TimingDynamicInvocationHandler(Object target) {
|
||||||
this.target = target;
|
this.target = target;
|
||||||
|
|
||||||
for(Method method: target.getClass().getDeclaredMethods()) {
|
for(Method method: target.getClass().getDeclaredMethods()) {
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
package com.baeldung.equalshashcode.entities;
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
import java.awt.Color;
|
import java.awt.*;
|
||||||
|
|
||||||
public class Square extends Rectangle {
|
public class Square extends Rectangle {
|
||||||
|
|
||||||
Color color;
|
private Color color;
|
||||||
|
|
||||||
public Square(double width, Color color) {
|
public Square(double width, Color color) {
|
||||||
super(width, width);
|
super(width, width);
|
||||||
|
@ -8,7 +8,7 @@ import javax.naming.InitialContext;
|
|||||||
import javax.naming.NamingException;
|
import javax.naming.NamingException;
|
||||||
|
|
||||||
public class LookupFSJNDI {
|
public class LookupFSJNDI {
|
||||||
InitialContext ctx = null;
|
private InitialContext ctx = null;
|
||||||
|
|
||||||
public LookupFSJNDI() throws NamingException {
|
public LookupFSJNDI() throws NamingException {
|
||||||
super();
|
super();
|
||||||
|
@ -4,7 +4,7 @@ public class Person {
|
|||||||
private String name;
|
private String name;
|
||||||
private int age;
|
private int age;
|
||||||
|
|
||||||
public Person(String name, int age) {
|
Person(String name, int age) {
|
||||||
super();
|
super();
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.age = age;
|
this.age = age;
|
||||||
|
@ -4,10 +4,10 @@ import io.vavr.collection.Seq;
|
|||||||
import io.vavr.control.Validation;
|
import io.vavr.control.Validation;
|
||||||
|
|
||||||
class PersonValidator {
|
class PersonValidator {
|
||||||
String NAME_ERR = "Invalid characters in name: ";
|
private static final String NAME_ERR = "Invalid characters in name: ";
|
||||||
String AGE_ERR = "Age must be at least 0";
|
private static final String AGE_ERR = "Age must be at least 0";
|
||||||
|
|
||||||
public Validation<Seq<String>, Person> validatePerson(String name, int age) {
|
Validation<Seq<String>, Person> validatePerson(String name, int age) {
|
||||||
return Validation.combine(validateName(name), validateAge(age)).ap(Person::new);
|
return Validation.combine(validateName(name), validateAge(age)).ap(Person::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -5,14 +5,14 @@ import com.baeldung.vavr.exception.handling.client.HttpClient;
|
|||||||
import com.baeldung.vavr.exception.handling.client.Response;
|
import com.baeldung.vavr.exception.handling.client.Response;
|
||||||
import io.vavr.control.Try;
|
import io.vavr.control.Try;
|
||||||
|
|
||||||
public class VavrTry {
|
class VavrTry {
|
||||||
private final HttpClient httpClient;
|
private final HttpClient httpClient;
|
||||||
|
|
||||||
public VavrTry(HttpClient httpClient) {
|
VavrTry(HttpClient httpClient) {
|
||||||
this.httpClient = httpClient;
|
this.httpClient = httpClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Try<Response> getResponse() {
|
Try<Response> getResponse() {
|
||||||
return Try.of(httpClient::call);
|
return Try.of(httpClient::call);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user