Merge branch 'master' of https://github.com/ahmedtawila/tutorials
This commit is contained in:
@@ -327,6 +327,22 @@
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<configuration>
|
||||
<executable>java</executable>
|
||||
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
|
||||
<arguments>
|
||||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath/>
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
@@ -6,7 +6,7 @@ public class NumbersConsumer implements Runnable {
|
||||
private final BlockingQueue<Integer> queue;
|
||||
private final int poisonPill;
|
||||
|
||||
public NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
||||
NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
||||
this.queue = queue;
|
||||
this.poisonPill = poisonPill;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ public class NumbersProducer implements Runnable {
|
||||
private final int poisonPill;
|
||||
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.poisonPill = poisonPill;
|
||||
this.poisonPillPerProducer = poisonPillPerProducer;
|
||||
|
||||
@@ -7,7 +7,7 @@ public class BrokenWorker implements Runnable {
|
||||
private final List<String> outputScraper;
|
||||
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.countDownLatch = countDownLatch;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ public class WaitingWorker implements Runnable {
|
||||
private final CountDownLatch callingThreadBlocker;
|
||||
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.readyThreadCounter = readyThreadCounter;
|
||||
|
||||
@@ -7,7 +7,7 @@ public class Worker implements Runnable {
|
||||
private final List<String> outputScraper;
|
||||
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.countDownLatch = countDownLatch;
|
||||
}
|
||||
|
||||
+2
-7
@@ -7,9 +7,6 @@ import java.util.Random;
|
||||
import java.util.concurrent.BrokenBarrierException;
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
|
||||
/**
|
||||
* Created by cv on 24/6/17.
|
||||
*/
|
||||
public class CyclicBarrierDemo {
|
||||
|
||||
private CyclicBarrier cyclicBarrier;
|
||||
@@ -19,7 +16,7 @@ public class CyclicBarrierDemo {
|
||||
private int NUM_WORKERS;
|
||||
|
||||
|
||||
public void runSimulation(int numWorkers, int numberOfPartialResults) {
|
||||
private void runSimulation(int numWorkers, int numberOfPartialResults) {
|
||||
NUM_PARTIAL_RESULTS = numberOfPartialResults;
|
||||
NUM_WORKERS = numWorkers;
|
||||
|
||||
@@ -49,9 +46,7 @@ public class CyclicBarrierDemo {
|
||||
try {
|
||||
System.out.println(thisThreadName + " waiting for others to reach barrier.");
|
||||
cyclicBarrier.await();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} catch (BrokenBarrierException e) {
|
||||
} catch (InterruptedException | BrokenBarrierException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ public class DelayObject implements Delayed {
|
||||
private String data;
|
||||
private long startTime;
|
||||
|
||||
public DelayObject(String data, long delayInMilliseconds) {
|
||||
DelayObject(String data, long delayInMilliseconds) {
|
||||
this.data = data;
|
||||
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
|
||||
}
|
||||
|
||||
@@ -7,9 +7,9 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
public class DelayQueueConsumer implements Runnable {
|
||||
private BlockingQueue<DelayObject> queue;
|
||||
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.numberOfElementsToTake = numberOfElementsToTake;
|
||||
}
|
||||
|
||||
@@ -9,9 +9,9 @@ public class DelayQueueProducer implements Runnable {
|
||||
private final Integer numberOfElementsToProduce;
|
||||
private final Integer delayOfEachProducedMessageMilliseconds;
|
||||
|
||||
public DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
||||
Integer numberOfElementsToProduce,
|
||||
Integer delayOfEachProducedMessageMilliseconds) {
|
||||
DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
||||
Integer numberOfElementsToProduce,
|
||||
Integer delayOfEachProducedMessageMilliseconds) {
|
||||
this.queue = queue;
|
||||
this.numberOfElementsToProduce = numberOfElementsToProduce;
|
||||
this.delayOfEachProducedMessageMilliseconds = delayOfEachProducedMessageMilliseconds;
|
||||
|
||||
@@ -5,7 +5,7 @@ public class Philosopher implements Runnable {
|
||||
private final Object leftFork;
|
||||
private final Object rightFork;
|
||||
|
||||
public Philosopher(Object left, Object right) {
|
||||
Philosopher(Object left, Object right) {
|
||||
this.leftFork = left;
|
||||
this.rightFork = right;
|
||||
}
|
||||
@@ -30,7 +30,6 @@ public class Philosopher implements Runnable {
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -7,7 +7,7 @@ public class FactorialSquareCalculator extends RecursiveTask<Integer> {
|
||||
|
||||
final private Integer n;
|
||||
|
||||
public FactorialSquareCalculator(Integer n) {
|
||||
FactorialSquareCalculator(Integer n) {
|
||||
this.n = n;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,15 +3,15 @@ package com.baeldung.concurrent.future;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class SquareCalculator {
|
||||
class SquareCalculator {
|
||||
|
||||
private final ExecutorService executor;
|
||||
|
||||
public SquareCalculator(ExecutorService executor) {
|
||||
SquareCalculator(ExecutorService executor) {
|
||||
this.executor = executor;
|
||||
}
|
||||
|
||||
public Future<Integer> calculate(Integer input) {
|
||||
Future<Integer> calculate(Integer input) {
|
||||
return executor.submit(() -> {
|
||||
Thread.sleep(1000);
|
||||
return input * input;
|
||||
|
||||
+57
-57
@@ -13,71 +13,71 @@ import static java.lang.Thread.sleep;
|
||||
|
||||
public class ReentrantLockWithCondition {
|
||||
|
||||
static Logger logger = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
|
||||
private static Logger LOG = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
|
||||
|
||||
Stack<String> stack = new Stack<>();
|
||||
int CAPACITY = 5;
|
||||
private Stack<String> stack = new Stack<>();
|
||||
private static final int CAPACITY = 5;
|
||||
|
||||
ReentrantLock lock = new ReentrantLock();
|
||||
Condition stackEmptyCondition = lock.newCondition();
|
||||
Condition stackFullCondition = lock.newCondition();
|
||||
private ReentrantLock lock = new ReentrantLock();
|
||||
private Condition stackEmptyCondition = lock.newCondition();
|
||||
private Condition stackFullCondition = lock.newCondition();
|
||||
|
||||
public void pushToStack(String item) throws InterruptedException {
|
||||
try {
|
||||
lock.lock();
|
||||
if (stack.size() == CAPACITY) {
|
||||
logger.info(Thread.currentThread().getName() + " wait on stack full");
|
||||
stackFullCondition.await();
|
||||
}
|
||||
logger.info("Pushing the item " + item);
|
||||
stack.push(item);
|
||||
stackEmptyCondition.signalAll();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public String popFromStack() throws InterruptedException {
|
||||
try {
|
||||
lock.lock();
|
||||
if (stack.size() == 0) {
|
||||
logger.info(Thread.currentThread().getName() + " wait on stack empty");
|
||||
stackEmptyCondition.await();
|
||||
}
|
||||
return stack.pop();
|
||||
} finally {
|
||||
stackFullCondition.signalAll();
|
||||
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();
|
||||
}
|
||||
}
|
||||
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 {
|
||||
logger.info("Item popped " + object.popFromStack());
|
||||
} 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();
|
||||
}
|
||||
service.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,81 +12,77 @@ import static java.lang.Thread.sleep;
|
||||
|
||||
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();
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||
try {
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||
counter++;
|
||||
} catch (Exception exception) {
|
||||
logger.error(" Interrupted Exception ", exception);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||
}
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
public void performTryLock() {
|
||||
private void performTryLock() {
|
||||
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
|
||||
try {
|
||||
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
|
||||
if (isLockAcquired) {
|
||||
try {
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||
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");
|
||||
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||
sleep(1000);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " released 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) {
|
||||
logger.error(" Interrupted Exception ", exception);
|
||||
}
|
||||
logger.info("Thread - " + Thread.currentThread().getName() + " could not acquire 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;
|
||||
}
|
||||
public ReentrantLock getLock() {
|
||||
return lock;
|
||||
}
|
||||
|
||||
boolean isLocked() {
|
||||
return lock.isLocked();
|
||||
}
|
||||
boolean isLocked() {
|
||||
return lock.isLocked();
|
||||
}
|
||||
|
||||
boolean hasQueuedThreads() {
|
||||
return lock.hasQueuedThreads();
|
||||
}
|
||||
boolean hasQueuedThreads() {
|
||||
return lock.hasQueuedThreads();
|
||||
}
|
||||
|
||||
int getCounter() {
|
||||
return counter;
|
||||
}
|
||||
int getCounter() {
|
||||
return counter;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
public static void main(String[] args) {
|
||||
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
service.execute(() -> {
|
||||
object.perform();
|
||||
});
|
||||
service.execute(() -> {
|
||||
object.performTryLock();
|
||||
});
|
||||
service.execute(object::perform);
|
||||
service.execute(object::performTryLock);
|
||||
|
||||
service.shutdown();
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -12,93 +12,93 @@ import java.util.concurrent.locks.StampedLock;
|
||||
import static java.lang.Thread.sleep;
|
||||
|
||||
public class StampedLockDemo {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
|
||||
private Map<String, String> map = new HashMap<>();
|
||||
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 {
|
||||
long stamp = lock.writeLock();
|
||||
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);
|
||||
}
|
||||
}
|
||||
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);
|
||||
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);
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public String readWithOptimisticLock(String key) throws InterruptedException {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
String value = map.get(key);
|
||||
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);
|
||||
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);
|
||||
} finally {
|
||||
lock.unlock(stamp);
|
||||
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
|
||||
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
StampedLockDemo object = new StampedLockDemo();
|
||||
public static void main(String[] args) {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
StampedLockDemo object = new StampedLockDemo();
|
||||
|
||||
Runnable writeTask = () -> {
|
||||
Runnable writeTask = () -> {
|
||||
|
||||
try {
|
||||
object.put("key1", "value1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
Runnable readTask = () -> {
|
||||
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.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);
|
||||
try {
|
||||
object.readWithOptimisticLock("key1");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
};
|
||||
service.submit(writeTask);
|
||||
service.submit(writeTask);
|
||||
service.submit(readTask);
|
||||
service.submit(readOptimisticTask);
|
||||
|
||||
service.shutdown();
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+81
-81
@@ -15,106 +15,106 @@ import static java.lang.Thread.sleep;
|
||||
|
||||
public class SynchronizedHashMapWithRWLock {
|
||||
|
||||
static Map<String, String> syncHashMap = new HashMap<>();
|
||||
Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
|
||||
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();
|
||||
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 {
|
||||
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();
|
||||
}
|
||||
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 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 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();
|
||||
}
|
||||
}
|
||||
public boolean containsKey(String key) {
|
||||
try {
|
||||
readLock.lock();
|
||||
return syncHashMap.containsKey(key);
|
||||
} finally {
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
boolean isReadLockAvailable() {
|
||||
return readLock.tryLock();
|
||||
}
|
||||
boolean isReadLockAvailable() {
|
||||
return readLock.tryLock();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
|
||||
final int threadCount = 3;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
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.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();
|
||||
}
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
private static class Reader implements Runnable {
|
||||
private static class Reader implements Runnable {
|
||||
|
||||
SynchronizedHashMapWithRWLock object;
|
||||
SynchronizedHashMapWithRWLock object;
|
||||
|
||||
public Reader(SynchronizedHashMapWithRWLock object) {
|
||||
this.object = object;
|
||||
}
|
||||
Reader(SynchronizedHashMapWithRWLock object) {
|
||||
this.object = object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
object.get("key" + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 0; i < 10; 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) {
|
||||
this.object = 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
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
@@ -0,0 +1,23 @@
|
||||
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
@@ -0,0 +1,25 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,20 +2,20 @@ package com.baeldung.concurrent.skiplist;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
public class Event {
|
||||
class Event {
|
||||
private final ZonedDateTime eventTime;
|
||||
private final String content;
|
||||
|
||||
public Event(ZonedDateTime eventTime, String content) {
|
||||
Event(ZonedDateTime eventTime, String content) {
|
||||
this.eventTime = eventTime;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public ZonedDateTime getEventTime() {
|
||||
ZonedDateTime getEventTime() {
|
||||
return eventTime;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
String getContent() {
|
||||
return content;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,24 +5,24 @@ import java.util.Comparator;
|
||||
import java.util.concurrent.ConcurrentNavigableMap;
|
||||
import java.util.concurrent.ConcurrentSkipListMap;
|
||||
|
||||
public class EventWindowSort {
|
||||
class EventWindowSort {
|
||||
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());
|
||||
}
|
||||
|
||||
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
|
||||
ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
|
||||
return events.tailMap(ZonedDateTime
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
}
|
||||
|
||||
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
||||
ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
||||
return events.headMap(ZonedDateTime
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -13,10 +13,10 @@ public class WaitSleepExample {
|
||||
private static final Object LOCK = new Object();
|
||||
|
||||
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
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+4
-4
@@ -5,13 +5,13 @@ public class BaeldungSynchronizedBlocks {
|
||||
private int count = 0;
|
||||
private static int staticCount = 0;
|
||||
|
||||
public void performSynchronisedTask() {
|
||||
void performSynchronisedTask() {
|
||||
synchronized (this) {
|
||||
setCount(getCount() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
public static void performStaticSyncTask() {
|
||||
static void performStaticSyncTask() {
|
||||
synchronized (BaeldungSynchronizedBlocks.class) {
|
||||
setStaticCount(getStaticCount() + 1);
|
||||
}
|
||||
@@ -25,11 +25,11 @@ public class BaeldungSynchronizedBlocks {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public static int getStaticCount() {
|
||||
static int getStaticCount() {
|
||||
return staticCount;
|
||||
}
|
||||
|
||||
public static void setStaticCount(int staticCount) {
|
||||
private static void setStaticCount(int staticCount) {
|
||||
BaeldungSynchronizedBlocks.staticCount = staticCount;
|
||||
}
|
||||
}
|
||||
|
||||
+6
-6
@@ -5,17 +5,17 @@ public class BaeldungSynchronizedMethods {
|
||||
private int sum = 0;
|
||||
private int syncSum = 0;
|
||||
|
||||
public static int staticSum = 0;
|
||||
static int staticSum = 0;
|
||||
|
||||
public void calculate() {
|
||||
void calculate() {
|
||||
setSum(getSum() + 1);
|
||||
}
|
||||
|
||||
public synchronized void synchronisedCalculate() {
|
||||
synchronized void synchronisedCalculate() {
|
||||
setSyncSum(getSyncSum() + 1);
|
||||
}
|
||||
|
||||
public static synchronized void syncStaticCalculate() {
|
||||
static synchronized void syncStaticCalculate() {
|
||||
staticSum = staticSum + 1;
|
||||
}
|
||||
|
||||
@@ -27,11 +27,11 @@ public class BaeldungSynchronizedMethods {
|
||||
this.sum = sum;
|
||||
}
|
||||
|
||||
public int getSyncSum() {
|
||||
int getSyncSum() {
|
||||
return syncSum;
|
||||
}
|
||||
|
||||
public void setSyncSum(int syncSum) {
|
||||
private void setSyncSum(int syncSum) {
|
||||
this.syncSum = syncSum;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,40 +6,40 @@ import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
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);
|
||||
}
|
||||
|
||||
public LocalDate getLocalDateUsingParseMethod(String representation) {
|
||||
LocalDate getLocalDateUsingParseMethod(String representation) {
|
||||
return LocalDate.parse(representation);
|
||||
}
|
||||
|
||||
public LocalDate getLocalDateFromClock() {
|
||||
LocalDate getLocalDateFromClock() {
|
||||
LocalDate localDate = LocalDate.now();
|
||||
return localDate;
|
||||
}
|
||||
|
||||
public LocalDate getNextDay(LocalDate localDate) {
|
||||
LocalDate getNextDay(LocalDate localDate) {
|
||||
return localDate.plusDays(1);
|
||||
}
|
||||
|
||||
public LocalDate getPreviousDay(LocalDate localDate) {
|
||||
LocalDate getPreviousDay(LocalDate localDate) {
|
||||
return localDate.minus(1, ChronoUnit.DAYS);
|
||||
}
|
||||
|
||||
public DayOfWeek getDayOfWeek(LocalDate localDate) {
|
||||
DayOfWeek getDayOfWeek(LocalDate localDate) {
|
||||
DayOfWeek day = localDate.getDayOfWeek();
|
||||
return day;
|
||||
}
|
||||
|
||||
public LocalDate getFirstDayOfMonth() {
|
||||
LocalDate getFirstDayOfMonth() {
|
||||
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
||||
return firstDayOfMonth;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartOfDay(LocalDate localDate) {
|
||||
LocalDateTime getStartOfDay(LocalDate localDate) {
|
||||
LocalDateTime startofDay = localDate.atStartOfDay();
|
||||
return startofDay;
|
||||
}
|
||||
|
||||
@@ -5,31 +5,27 @@ import java.time.temporal.ChronoUnit;
|
||||
|
||||
public class UseLocalTime {
|
||||
|
||||
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
||||
LocalTime localTime = LocalTime.of(hour, min, seconds);
|
||||
return localTime;
|
||||
LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
||||
return LocalTime.of(hour, min, seconds);
|
||||
}
|
||||
|
||||
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
||||
LocalTime localTime = LocalTime.parse(timeRepresentation);
|
||||
return localTime;
|
||||
LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
||||
return LocalTime.parse(timeRepresentation);
|
||||
}
|
||||
|
||||
public LocalTime getLocalTimeFromClock() {
|
||||
LocalTime localTime = LocalTime.now();
|
||||
return localTime;
|
||||
private LocalTime getLocalTimeFromClock() {
|
||||
return LocalTime.now();
|
||||
}
|
||||
|
||||
public LocalTime addAnHour(LocalTime localTime) {
|
||||
LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS);
|
||||
return newTime;
|
||||
LocalTime addAnHour(LocalTime localTime) {
|
||||
return localTime.plus(1, ChronoUnit.HOURS);
|
||||
}
|
||||
|
||||
public int getHourFromLocalTime(LocalTime localTime) {
|
||||
int getHourFromLocalTime(LocalTime localTime) {
|
||||
return localTime.getHour();
|
||||
}
|
||||
|
||||
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
||||
LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
||||
return localTime.withMinute(minute);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,13 +3,13 @@ package com.baeldung.datetime;
|
||||
import java.time.LocalDate;
|
||||
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);
|
||||
}
|
||||
|
||||
public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
||||
Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
||||
return Period.between(localDate1, localDate2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,12 +8,10 @@ import java.util.Date;
|
||||
public class UseToInstant {
|
||||
|
||||
public LocalDateTime convertDateToLocalDate(Date date) {
|
||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||
return localDateTime;
|
||||
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
|
||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||
return localDateTime;
|
||||
return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,10 +4,9 @@ import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
public class UseZonedDateTime {
|
||||
class UseZonedDateTime {
|
||||
|
||||
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
|
||||
return zonedDateTime;
|
||||
ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
||||
return ZonedDateTime.of(localDateTime, zoneId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.deserialization;
|
||||
|
||||
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)
|
||||
|
||||
public String headphonePort;
|
||||
public String thunderboltPort;
|
||||
public String lighteningPort;
|
||||
|
||||
public String getHeadphonePort() {
|
||||
return headphonePort;
|
||||
}
|
||||
|
||||
public String getThunderboltPort() {
|
||||
return thunderboltPort;
|
||||
}
|
||||
|
||||
public static long getSerialVersionUID() {
|
||||
return serialVersionUID;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.deserialization;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.util.Base64;
|
||||
|
||||
public class DeserializationUtility {
|
||||
|
||||
public static void main(String[] args) throws ClassNotFoundException, IOException {
|
||||
|
||||
String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
|
||||
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());
|
||||
}
|
||||
|
||||
public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException {
|
||||
byte[] data = Base64.getDecoder().decode(s);
|
||||
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
|
||||
Object o = ois.readObject();
|
||||
ois.close();
|
||||
return o;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.deserialization;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.util.Base64;
|
||||
|
||||
public class SerializationUtility {
|
||||
|
||||
public static void main(String[] args) throws ClassNotFoundException, IOException {
|
||||
|
||||
AppleProduct macBook = new AppleProduct();
|
||||
macBook.headphonePort = "headphonePort2020";
|
||||
macBook.thunderboltPort = "thunderboltPort2020";
|
||||
|
||||
String serializedObj = serializeObjectToString(macBook);
|
||||
System.out.println("Serialized AppleProduct object to string:");
|
||||
System.out.println(serializedObj);
|
||||
}
|
||||
|
||||
public static String serializeObjectToString(Serializable o) throws IOException {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(baos);
|
||||
oos.writeObject(o);
|
||||
oos.close();
|
||||
return Base64.getEncoder().encodeToString(baos.toByteArray());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,8 +13,7 @@ public class DirectoryMonitoringExample {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
|
||||
|
||||
|
||||
public static final int POLL_INTERVAL = 500;
|
||||
private static final int POLL_INTERVAL = 500;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
|
||||
|
||||
@@ -6,12 +6,12 @@ public class Computer {
|
||||
private String color;
|
||||
private Integer healty;
|
||||
|
||||
public Computer(final int age, final String color) {
|
||||
Computer(final int age, final String color) {
|
||||
this.age = age;
|
||||
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.color = color;
|
||||
this.healty = healty;
|
||||
@@ -28,7 +28,7 @@ public class Computer {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getColor() {
|
||||
String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
@@ -36,11 +36,11 @@ public class Computer {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public Integer getHealty() {
|
||||
Integer getHealty() {
|
||||
return healty;
|
||||
}
|
||||
|
||||
public void setHealty(final Integer healty) {
|
||||
void setHealty(final Integer healty) {
|
||||
this.healty = healty;
|
||||
}
|
||||
|
||||
@@ -72,10 +72,7 @@ public class Computer {
|
||||
|
||||
final Computer computer = (Computer) o;
|
||||
|
||||
if (age != null ? !age.equals(computer.age) : computer.age != null) {
|
||||
return false;
|
||||
}
|
||||
return color != null ? color.equals(computer.color) : computer.color == null;
|
||||
return (age != null ? age.equals(computer.age) : computer.age == null) && (color != null ? color.equals(computer.color) : computer.color == null);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@ import java.util.List;
|
||||
|
||||
public class ComputerUtils {
|
||||
|
||||
public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
||||
public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
||||
static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
||||
static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
||||
|
||||
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
||||
|
||||
@@ -18,7 +18,7 @@ public class ComputerUtils {
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void repair(final Computer computer) {
|
||||
static void repair(final Computer computer) {
|
||||
if (computer.getHealty() < 50) {
|
||||
computer.setHealty(100);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ public class MacbookPro extends Computer {
|
||||
super(age, color);
|
||||
}
|
||||
|
||||
public MacbookPro(Integer age, String color, Integer healty) {
|
||||
MacbookPro(Integer age, String color, Integer healty) {
|
||||
super(age, color, healty);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ public class TimingDynamicInvocationHandler implements InvocationHandler {
|
||||
|
||||
private Object target;
|
||||
|
||||
public TimingDynamicInvocationHandler(Object target) {
|
||||
TimingDynamicInvocationHandler(Object target) {
|
||||
this.target = target;
|
||||
|
||||
for(Method method: target.getClass().getDeclaredMethods()) {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.*;
|
||||
|
||||
public class Square extends Rectangle {
|
||||
|
||||
Color color;
|
||||
private Color color;
|
||||
|
||||
public Square(double width, Color color) {
|
||||
super(width, width);
|
||||
|
||||
@@ -8,7 +8,7 @@ import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
|
||||
public class LookupFSJNDI {
|
||||
InitialContext ctx = null;
|
||||
private InitialContext ctx = null;
|
||||
|
||||
public LookupFSJNDI() throws NamingException {
|
||||
super();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
public class BigDecimalImpl {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
BigDecimal serviceTax = new BigDecimal("56.0084578639");
|
||||
serviceTax = serviceTax.setScale(2, RoundingMode.CEILING);
|
||||
|
||||
BigDecimal entertainmentTax = new BigDecimal("23.00689");
|
||||
entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR);
|
||||
|
||||
BigDecimal totalTax = serviceTax.add(entertainmentTax);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class BigIntegerImpl {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
|
||||
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
|
||||
|
||||
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -11,4 +11,4 @@ public class NoClassDefFoundErrorExample {
|
||||
test = new ClassWithInitErrors();
|
||||
return test;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.outofmemoryerror;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
||||
public class OutOfMemoryGCLimitExceed {
|
||||
public static void addRandomDataToMap() {
|
||||
Map<Integer, String> dataMap = new HashMap<>();
|
||||
Random r = new Random();
|
||||
while (true) {
|
||||
dataMap.put(r.nextInt(), String.valueOf(r.nextInt()));
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
OutOfMemoryGCLimitExceed.addRandomDataToMap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.typeerasure;
|
||||
|
||||
public class ArrayContentPrintUtil {
|
||||
|
||||
public static <E> void printArray(E[] array) {
|
||||
for (E element : array) {
|
||||
System.out.printf("%s ", element);
|
||||
}
|
||||
}
|
||||
|
||||
public static <E extends Comparable<E>> void printArray(E[] array) {
|
||||
for (E element : array) {
|
||||
System.out.printf("%s ", element);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.typeerasure;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class BoundStack<E extends Comparable<E>> {
|
||||
|
||||
private E[] stackContent;
|
||||
private int total;
|
||||
|
||||
public BoundStack(int capacity) {
|
||||
this.stackContent = (E[]) new Object[capacity];
|
||||
}
|
||||
|
||||
public void push(E data) {
|
||||
if (total == stackContent.length) {
|
||||
resize(2 * stackContent.length);
|
||||
}
|
||||
stackContent[total++] = data;
|
||||
}
|
||||
|
||||
public E pop() {
|
||||
if (!isEmpty()) {
|
||||
E datum = stackContent[total];
|
||||
stackContent[total--] = null;
|
||||
return datum;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void resize(int capacity) {
|
||||
Arrays.copyOf(stackContent, capacity);
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return total == 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.typeerasure;
|
||||
|
||||
public class IntegerStack extends Stack<Integer> {
|
||||
|
||||
public IntegerStack(int capacity) {
|
||||
super(capacity);
|
||||
}
|
||||
|
||||
public void push(Integer value) {
|
||||
System.out.println("Pushing into my integerStack");
|
||||
super.push(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.typeerasure;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class Stack<E> {
|
||||
|
||||
private E[] stackContent;
|
||||
private int total;
|
||||
|
||||
public Stack(int capacity) {
|
||||
this.stackContent = (E[]) new Object[capacity];
|
||||
}
|
||||
|
||||
public void push(E data) {
|
||||
System.out.println("In base stack push#");
|
||||
if (total == stackContent.length) {
|
||||
resize(2 * stackContent.length);
|
||||
}
|
||||
stackContent[total++] = data;
|
||||
}
|
||||
|
||||
public E pop() {
|
||||
if (!isEmpty()) {
|
||||
E datum = stackContent[total];
|
||||
stackContent[total--] = null;
|
||||
return datum;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void resize(int capacity) {
|
||||
Arrays.copyOf(stackContent, capacity);
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return total == 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ArrayCopyUtilUnitTest {
|
||||
private static Employee[] employees;
|
||||
private static final int MAX = 2;
|
||||
@@ -46,10 +48,10 @@ public class ArrayCopyUtilUnitTest {
|
||||
|
||||
System.arraycopy(array, 2, copiedArray, 0, 3);
|
||||
|
||||
Assert.assertTrue(3 == copiedArray.length);
|
||||
Assert.assertTrue(copiedArray[0] == array[2]);
|
||||
Assert.assertTrue(copiedArray[1] == array[3]);
|
||||
Assert.assertTrue(copiedArray[2] == array[4]);
|
||||
assertTrue(3 == copiedArray.length);
|
||||
assertTrue(copiedArray[0] == array[2]);
|
||||
assertTrue(copiedArray[1] == array[3]);
|
||||
assertTrue(copiedArray[2] == array[4]);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -58,10 +60,10 @@ public class ArrayCopyUtilUnitTest {
|
||||
|
||||
int[] copiedArray = Arrays.copyOfRange(array, 1, 4);
|
||||
|
||||
Assert.assertTrue(3 == copiedArray.length);
|
||||
Assert.assertTrue(copiedArray[0] == array[1]);
|
||||
Assert.assertTrue(copiedArray[1] == array[2]);
|
||||
Assert.assertTrue(copiedArray[2] == array[3]);
|
||||
assertTrue(3 == copiedArray.length);
|
||||
assertTrue(copiedArray[0] == array[1]);
|
||||
assertTrue(copiedArray[1] == array[2]);
|
||||
assertTrue(copiedArray[2] == array[3]);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -73,9 +75,9 @@ public class ArrayCopyUtilUnitTest {
|
||||
|
||||
Assert.assertArrayEquals(copiedArray, array);
|
||||
array[0] = 9;
|
||||
Assert.assertTrue(copiedArray[0] != array[0]);
|
||||
assertTrue(copiedArray[0] != array[0]);
|
||||
copiedArray[1] = 12;
|
||||
Assert.assertTrue(copiedArray[1] != array[1]);
|
||||
assertTrue(copiedArray[1] != array[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -85,7 +87,7 @@ public class ArrayCopyUtilUnitTest {
|
||||
Assert.assertArrayEquals(copiedArray, employees);
|
||||
employees[0].setName(employees[0].getName()+"_Changed");
|
||||
//change in employees' element caused change in the copied array
|
||||
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
|
||||
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -96,9 +98,9 @@ public class ArrayCopyUtilUnitTest {
|
||||
|
||||
Assert.assertArrayEquals(copiedArray, array);
|
||||
array[0] = 9;
|
||||
Assert.assertTrue(copiedArray[0] != array[0]);
|
||||
assertTrue(copiedArray[0] != array[0]);
|
||||
copiedArray[1] = 12;
|
||||
Assert.assertTrue(copiedArray[1] != array[1]);
|
||||
assertTrue(copiedArray[1] != array[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -108,7 +110,7 @@ public class ArrayCopyUtilUnitTest {
|
||||
Assert.assertArrayEquals(copiedArray, employees);;
|
||||
employees[0].setName(employees[0].getName()+"_Changed");
|
||||
//change in employees' element changed the copied array
|
||||
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
|
||||
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -138,7 +140,7 @@ public class ArrayCopyUtilUnitTest {
|
||||
Assert.assertArrayEquals(copiedArray, employees);
|
||||
employees[0].setName(employees[0].getName()+"_Changed");
|
||||
//change in employees' element didn't change in the copied array
|
||||
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
|
||||
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -8,4 +8,4 @@ public class ClassNotFoundExceptionTest {
|
||||
public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException {
|
||||
Class.forName("oracle.jdbc.driver.OracleDriver");
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -24,7 +24,7 @@ public class CompletableFutureLongRunningUnitTest {
|
||||
assertEquals("Hello", result);
|
||||
}
|
||||
|
||||
public Future<String> calculateAsync() throws InterruptedException {
|
||||
private Future<String> calculateAsync() throws InterruptedException {
|
||||
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||
|
||||
Executors.newCachedThreadPool().submit(() -> {
|
||||
@@ -44,7 +44,7 @@ public class CompletableFutureLongRunningUnitTest {
|
||||
assertEquals("Hello", result);
|
||||
}
|
||||
|
||||
public Future<String> calculateAsyncWithCancellation() throws InterruptedException {
|
||||
private Future<String> calculateAsyncWithCancellation() throws InterruptedException {
|
||||
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||
|
||||
Executors.newCachedThreadPool().submit(() -> {
|
||||
|
||||
+2
-2
@@ -24,8 +24,8 @@ public class LongAccumulatorUnitTest {
|
||||
|
||||
//when
|
||||
Runnable accumulateAction = () -> IntStream
|
||||
.rangeClosed(0, numberOfIncrements)
|
||||
.forEach(accumulator::accumulate);
|
||||
.rangeClosed(0, numberOfIncrements)
|
||||
.forEach(accumulator::accumulate);
|
||||
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
executorService.execute(accumulateAction);
|
||||
|
||||
+2
-2
@@ -17,7 +17,7 @@ public class CopyOnWriteArrayListUnitTest {
|
||||
public void givenCopyOnWriteList_whenIterateAndAddElementToUnderneathList_thenShouldNotChangeIterator() {
|
||||
//given
|
||||
final CopyOnWriteArrayList<Integer> numbers =
|
||||
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
|
||||
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
|
||||
|
||||
//when
|
||||
Iterator<Integer> iterator = numbers.iterator();
|
||||
@@ -42,7 +42,7 @@ public class CopyOnWriteArrayListUnitTest {
|
||||
public void givenCopyOnWriteList_whenIterateOverItAndTryToRemoveElement_thenShouldThrowException() {
|
||||
//given
|
||||
final CopyOnWriteArrayList<Integer> numbers =
|
||||
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
|
||||
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
|
||||
|
||||
//when
|
||||
Iterator<Integer> iterator = numbers.iterator();
|
||||
|
||||
+8
-4
@@ -4,7 +4,11 @@ import org.junit.FixMethodOrder;
|
||||
import org.junit.Test;
|
||||
import org.junit.runners.MethodSorters;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.DelayQueue;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
@@ -19,7 +23,7 @@ public class DelayQueueIntegrationTest {
|
||||
int delayOfEachProducedMessageMilliseconds = 500;
|
||||
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
|
||||
DelayQueueProducer producer
|
||||
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
|
||||
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
|
||||
|
||||
//when
|
||||
executor.submit(producer);
|
||||
@@ -41,7 +45,7 @@ public class DelayQueueIntegrationTest {
|
||||
int delayOfEachProducedMessageMilliseconds = 10_000;
|
||||
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
|
||||
DelayQueueProducer producer
|
||||
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
|
||||
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
|
||||
|
||||
//when
|
||||
executor.submit(producer);
|
||||
@@ -63,7 +67,7 @@ public class DelayQueueIntegrationTest {
|
||||
int delayOfEachProducedMessageMilliseconds = -10_000;
|
||||
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
|
||||
DelayQueueProducer producer
|
||||
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
|
||||
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
|
||||
|
||||
//when
|
||||
executor.submit(producer);
|
||||
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
package com.baeldung.concurrent.future;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class FactorialSquareCalculatorUnitTest {
|
||||
|
||||
|
||||
+6
-1
@@ -8,7 +8,12 @@ import org.junit.rules.TestName;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
+41
-41
@@ -9,65 +9,65 @@ import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class SharedObjectWithLockManualTest {
|
||||
|
||||
@Test
|
||||
public void whenLockAcquired_ThenLockedIsTrue() {
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
@Test
|
||||
public void whenLockAcquired_ThenLockedIsTrue() {
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
|
||||
executeThreads(object, threadCount, service);
|
||||
executeThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(true, object.isLocked());
|
||||
assertEquals(true, object.isLocked());
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLocked_ThenQueuedThread() {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
@Test
|
||||
public void whenLocked_ThenQueuedThread() {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
executeThreads(object, threadCount, service);
|
||||
executeThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(object.hasQueuedThreads(), true);
|
||||
assertEquals(object.hasQueuedThreads(), true);
|
||||
|
||||
service.shutdown();
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public void whenTryLock_ThenQueuedThread() {
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
public void whenTryLock_ThenQueuedThread() {
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final int threadCount = 2;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
|
||||
executeThreads(object, threadCount, service);
|
||||
executeThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(true, object.isLocked());
|
||||
assertEquals(true, object.isLocked());
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetCount_ThenCorrectCount() throws InterruptedException {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
@Test
|
||||
public void whenGetCount_ThenCorrectCount() throws InterruptedException {
|
||||
final int threadCount = 4;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||
|
||||
executeThreads(object, threadCount, service);
|
||||
Thread.sleep(1000);
|
||||
assertEquals(object.getCounter(), 4);
|
||||
executeThreads(object, threadCount, service);
|
||||
Thread.sleep(1000);
|
||||
assertEquals(object.getCounter(), 4);
|
||||
|
||||
service.shutdown();
|
||||
service.shutdown();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
service.execute(object::perform);
|
||||
}
|
||||
}
|
||||
private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
service.execute(object::perform);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+35
-36
@@ -1,6 +1,5 @@
|
||||
package com.baeldung.concurrent.locks;
|
||||
|
||||
import jdk.nashorn.internal.ir.annotations.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -10,49 +9,49 @@ import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class SynchronizedHashMapWithRWLockManualTest {
|
||||
|
||||
@Test
|
||||
public void whenWriting_ThenNoReading() {
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
final int threadCount = 3;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
@Test
|
||||
public void whenWriting_ThenNoReading() {
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
final int threadCount = 3;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
|
||||
executeWriterThreads(object, threadCount, service);
|
||||
executeWriterThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(object.isReadLockAvailable(), false);
|
||||
assertEquals(object.isReadLockAvailable(), false);
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReading_ThenMultipleReadingAllowed() {
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
final int threadCount = 5;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
@Test
|
||||
public void whenReading_ThenMultipleReadingAllowed() {
|
||||
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
|
||||
final int threadCount = 5;
|
||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||
|
||||
executeReaderThreads(object, threadCount, service);
|
||||
executeReaderThreads(object, threadCount, service);
|
||||
|
||||
assertEquals(object.isReadLockAvailable(), true);
|
||||
assertEquals(object.isReadLockAvailable(), true);
|
||||
|
||||
service.shutdown();
|
||||
}
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
service.execute(() -> {
|
||||
try {
|
||||
object.put("key" + threadCount, "value" + threadCount);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
service.execute(() -> {
|
||||
try {
|
||||
object.put("key" + threadCount, "value" + threadCount);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++)
|
||||
service.execute(() -> {
|
||||
object.get("key" + threadCount);
|
||||
});
|
||||
}
|
||||
private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
|
||||
for (int i = 0; i < threadCount; i++)
|
||||
service.execute(() -> {
|
||||
object.get("key" + threadCount);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ public class PriorityBlockingQueueIntegrationTest {
|
||||
try {
|
||||
Integer poll = queue.take();
|
||||
LOG.debug("Polled: " + poll);
|
||||
} catch (InterruptedException e) {
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.baeldung.concurrent.semaphores;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class SemaphoresManualTest {
|
||||
|
||||
// ========= login queue ======
|
||||
|
||||
@Test
|
||||
public void givenLoginQueue_whenReachLimit_thenBlocked() {
|
||||
final int slots = 10;
|
||||
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
|
||||
final LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
|
||||
IntStream.range(0, slots)
|
||||
.forEach(user -> executorService.execute(loginQueue::tryLogin));
|
||||
executorService.shutdown();
|
||||
|
||||
assertEquals(0, loginQueue.availableSlots());
|
||||
assertFalse(loginQueue.tryLogin());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoginQueue_whenLogout_thenSlotsAvailable() {
|
||||
final int slots = 10;
|
||||
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
|
||||
final LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
|
||||
IntStream.range(0, slots)
|
||||
.forEach(user -> executorService.execute(loginQueue::tryLogin));
|
||||
executorService.shutdown();
|
||||
|
||||
assertEquals(0, loginQueue.availableSlots());
|
||||
loginQueue.logout();
|
||||
assertTrue(loginQueue.availableSlots() > 0);
|
||||
assertTrue(loginQueue.tryLogin());
|
||||
}
|
||||
|
||||
// ========= delay queue =======
|
||||
|
||||
@Test
|
||||
public void givenDelayQueue_whenReachLimit_thenBlocked() {
|
||||
final int slots = 50;
|
||||
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
|
||||
final DelayQueueUsingTimedSemaphore delayQueue = new DelayQueueUsingTimedSemaphore(1, slots);
|
||||
IntStream.range(0, slots)
|
||||
.forEach(user -> executorService.execute(delayQueue::tryAdd));
|
||||
executorService.shutdown();
|
||||
|
||||
assertEquals(0, delayQueue.availableSlots());
|
||||
assertFalse(delayQueue.tryAdd());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDelayQueue_whenTimePass_thenSlotsAvailable() throws InterruptedException {
|
||||
final int slots = 50;
|
||||
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
|
||||
final DelayQueueUsingTimedSemaphore delayQueue = new DelayQueueUsingTimedSemaphore(1, slots);
|
||||
IntStream.range(0, slots)
|
||||
.forEach(user -> executorService.execute(delayQueue::tryAdd));
|
||||
executorService.shutdown();
|
||||
|
||||
assertEquals(0, delayQueue.availableSlots());
|
||||
Thread.sleep(1000);
|
||||
assertTrue(delayQueue.availableSlots() > 0);
|
||||
assertTrue(delayQueue.tryAdd());
|
||||
}
|
||||
|
||||
// ========== mutex ========
|
||||
|
||||
@Test
|
||||
public void whenMutexAndMultipleThreads_thenBlocked() throws InterruptedException {
|
||||
final int count = 5;
|
||||
final ExecutorService executorService = Executors.newFixedThreadPool(count);
|
||||
final CounterUsingMutex counter = new CounterUsingMutex();
|
||||
IntStream.range(0, count)
|
||||
.forEach(user -> executorService.execute(() -> {
|
||||
try {
|
||||
counter.increase();
|
||||
} catch (final InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}));
|
||||
executorService.shutdown();
|
||||
|
||||
assertTrue(counter.hasQueuedThreads());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMutexAndMultipleThreads_ThenDelay_thenCorrectCount() throws InterruptedException {
|
||||
final int count = 5;
|
||||
final ExecutorService executorService = Executors.newFixedThreadPool(count);
|
||||
final CounterUsingMutex counter = new CounterUsingMutex();
|
||||
IntStream.range(0, count)
|
||||
.forEach(user -> executorService.execute(() -> {
|
||||
try {
|
||||
counter.increase();
|
||||
} catch (final InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}));
|
||||
executorService.shutdown();
|
||||
assertTrue(counter.hasQueuedThreads());
|
||||
Thread.sleep(5000);
|
||||
assertFalse(counter.hasQueuedThreads());
|
||||
assertEquals(count, counter.getCount());
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -1,13 +1,13 @@
|
||||
package com.baeldung.concurrent.synchronize;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class BaeldungSychronizedBlockTest {
|
||||
|
||||
@@ -17,7 +17,7 @@ public class BaeldungSychronizedBlockTest {
|
||||
BaeldungSynchronizedBlocks synchronizedBlocks = new BaeldungSynchronizedBlocks();
|
||||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
|
||||
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(1000, synchronizedBlocks.getCount());
|
||||
@@ -28,7 +28,7 @@ public class BaeldungSychronizedBlockTest {
|
||||
ExecutorService service = Executors.newCachedThreadPool();
|
||||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
|
||||
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
|
||||
|
||||
+6
-6
@@ -1,14 +1,14 @@
|
||||
package com.baeldung.concurrent.synchronize;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class BaeldungSynchronizeMethodsTest {
|
||||
|
||||
@@ -19,7 +19,7 @@ public class BaeldungSynchronizeMethodsTest {
|
||||
BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods();
|
||||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(method::calculate));
|
||||
.forEach(count -> service.submit(method::calculate));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(1000, method.getSum());
|
||||
@@ -31,7 +31,7 @@ public class BaeldungSynchronizeMethodsTest {
|
||||
BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods();
|
||||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(method::synchronisedCalculate));
|
||||
.forEach(count -> service.submit(method::synchronisedCalculate));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(1000, method.getSyncSum());
|
||||
@@ -42,7 +42,7 @@ public class BaeldungSynchronizeMethodsTest {
|
||||
ExecutorService service = Executors.newCachedThreadPool();
|
||||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate));
|
||||
.forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(1000, BaeldungSynchronizedMethods.staticSum);
|
||||
|
||||
@@ -7,13 +7,15 @@ import java.time.Month;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class UseLocalDateTimeUnitTest {
|
||||
|
||||
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingParse_thenLocalDateTime() {
|
||||
Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
|
||||
Assert.assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
|
||||
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
|
||||
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,48 +7,50 @@ import java.time.LocalDateTime;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class UseLocalDateUnitTest {
|
||||
|
||||
UseLocalDate useLocalDate = new UseLocalDate();
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
|
||||
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
|
||||
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingParse_thenLocalDate() {
|
||||
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
|
||||
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingClock_thenLocalDate() {
|
||||
Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
|
||||
assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingPlus_thenNextDay() {
|
||||
Assert.assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
|
||||
assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingMinus_thenPreviousDay() {
|
||||
Assert.assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
|
||||
assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() {
|
||||
Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
|
||||
assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
|
||||
Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
|
||||
assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() {
|
||||
Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
|
||||
assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.deserialization;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InvalidClassException;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DeserializationUnitTest {
|
||||
|
||||
private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
|
||||
|
||||
private static long userDefinedSerialVersionUID = 1234567L;
|
||||
|
||||
/**
|
||||
* Tests the deserialization of the original "AppleProduct" (no exceptions are thrown)
|
||||
* @throws ClassNotFoundException
|
||||
* @throws IOException
|
||||
*/
|
||||
@Test
|
||||
public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException {
|
||||
|
||||
assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
|
||||
|
||||
AppleProduct macBook = new AppleProduct();
|
||||
macBook.headphonePort = "headphonePort2020";
|
||||
macBook.thunderboltPort = "thunderboltPort2020";
|
||||
|
||||
// serializes the "AppleProduct" object
|
||||
String serializedProduct = SerializationUtility.serializeObjectToString(macBook);
|
||||
|
||||
// deserializes the "AppleProduct" object
|
||||
AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct);
|
||||
|
||||
assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort));
|
||||
assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the deserialization of the modified (non-compatible) "AppleProduct".
|
||||
* The test should result in an InvalidClassException being thrown.
|
||||
*
|
||||
* Note: to run this test:
|
||||
* 1. Modify the value of the serialVersionUID identifier in AppleProduct.java
|
||||
* 2. Remove the @Ignore annotation
|
||||
* 3. Run the test individually (do not run the entire set of tests)
|
||||
* 4. Revert the changes made in 1 & 2 (so that you're able to re-run the tests successfully)
|
||||
*
|
||||
* @throws ClassNotFoundException
|
||||
* @throws IOException
|
||||
*/
|
||||
@Ignore
|
||||
@Test(expected = InvalidClassException.class)
|
||||
public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException {
|
||||
|
||||
assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
|
||||
|
||||
// attempts to deserialize the "AppleProduct" object
|
||||
DeserializationUtility.deSerializeObjectFromString(serializedObj);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -83,7 +83,7 @@ public class ComputerUtilsUnitTest {
|
||||
|
||||
final TriFunction<Integer, String, Integer, MacbookPro> integerStringIntegerObjectTriFunction = MacbookPro::new;
|
||||
final MacbookPro macbookPro = integerStringIntegerObjectTriFunction.apply(2010, "black", 100);
|
||||
Double initialValue = new Double(999.99);
|
||||
Double initialValue = 999.99;
|
||||
final Double actualValue = macbookPro.calculateValue(initialValue);
|
||||
Assert.assertEquals(766.659, actualValue, 0.0);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,12 @@ import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
@@ -14,6 +19,10 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class FileOperationsManualTest {
|
||||
|
||||
@Test
|
||||
@@ -25,7 +34,7 @@ public class FileOperationsManualTest {
|
||||
InputStream inputStream = new FileInputStream(file);
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
Assert.assertEquals(expectedData, data.trim());
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -36,7 +45,7 @@ public class FileOperationsManualTest {
|
||||
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
Assert.assertEquals(expectedData, data.trim());
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -47,7 +56,7 @@ public class FileOperationsManualTest {
|
||||
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -61,7 +70,7 @@ public class FileOperationsManualTest {
|
||||
InputStream inputStream = urlConnection.getInputStream();
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -72,7 +81,7 @@ public class FileOperationsManualTest {
|
||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||
String data = FileUtils.readFileToString(file);
|
||||
|
||||
Assert.assertEquals(expectedData, data.trim());
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -84,7 +93,7 @@ public class FileOperationsManualTest {
|
||||
byte[] fileBytes = Files.readAllBytes(path);
|
||||
String data = new String(fileBytes);
|
||||
|
||||
Assert.assertEquals(expectedData, data.trim());
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -98,7 +107,7 @@ public class FileOperationsManualTest {
|
||||
lines.forEach(line -> data.append(line).append("\n"));
|
||||
lines.close();
|
||||
|
||||
Assert.assertEquals(expectedData, data.toString().trim());
|
||||
assertEquals(expectedData, data.toString().trim());
|
||||
}
|
||||
|
||||
private String readFromInputStream(InputStream inputStream) throws IOException {
|
||||
|
||||
+4
-6
@@ -1,15 +1,13 @@
|
||||
package com.baeldung.filesystem.jndi.test;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.io.File;
|
||||
import com.baeldung.filesystem.jndi.LookupFSJNDI;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import java.io.File;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.filesystem.jndi.LookupFSJNDI;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class LookupFSJNDIIntegrationTest {
|
||||
LookupFSJNDI fsjndi;
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ public class FunctionalInterfaceUnitTest {
|
||||
@Test
|
||||
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
||||
Map<String, Integer> nameMap = new HashMap<>();
|
||||
Integer value = nameMap.computeIfAbsent("John", s -> s.length());
|
||||
Integer value = nameMap.computeIfAbsent("John", String::length);
|
||||
|
||||
assertEquals(new Integer(4), nameMap.get("John"));
|
||||
assertEquals(new Integer(4), value);
|
||||
|
||||
@@ -2,7 +2,7 @@ package com.baeldung.hashing;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class SHA256HashingUnitTest {
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.baeldung.http;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.DataOutputStream;
|
||||
@@ -17,6 +16,9 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class HttpRequestLiveTest {
|
||||
|
||||
@Test
|
||||
@@ -39,7 +41,7 @@ public class HttpRequestLiveTest {
|
||||
int status = con.getResponseCode();
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
|
||||
String inputLine;
|
||||
StringBuffer content = new StringBuffer();
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
content.append(inputLine);
|
||||
}
|
||||
@@ -67,7 +69,7 @@ public class HttpRequestLiveTest {
|
||||
int status = con.getResponseCode();
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
|
||||
String inputLine;
|
||||
StringBuffer content = new StringBuffer();
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
content.append(inputLine);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.javanetworking.uriurl.test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.FixMethodOrder;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.baeldung.javanetworking.uriurl.URLDemo;
|
||||
|
||||
@FixMethodOrder
|
||||
public class URIDemoTest {
|
||||
private final Logger log = LoggerFactory.getLogger(URIDemoTest.class);
|
||||
String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||
// parsed locator
|
||||
static String URISCHEME = "https";
|
||||
String URISCHEMESPECIFIC;
|
||||
static String URIHOST = "wordpress.org";
|
||||
static String URIAUTHORITY = "wordpress.org:443";
|
||||
|
||||
static String URIPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||
int URIPORT = 443;
|
||||
static int URIDEFAULTPORT = 443;
|
||||
static String URIQUERY = "replies=3";
|
||||
static String URIFRAGMENT = "post-2278484";
|
||||
static String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIDEFAULTPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT;
|
||||
|
||||
static URI uri;
|
||||
URL url;
|
||||
BufferedReader in = null;
|
||||
String URIContent = "";
|
||||
|
||||
@BeforeClass
|
||||
public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws URISyntaxException {
|
||||
uri = new URI(URICOMPOUND);
|
||||
}
|
||||
|
||||
// check parsed URL
|
||||
@Test
|
||||
public void givenURI_whenURIIsParsed_thenSuccess() {
|
||||
assertNotNull("URI is null", uri);
|
||||
assertEquals("URI string is not equal", uri.toString(), URISTRING);
|
||||
assertEquals("Scheme is not equal", uri.getScheme(), URISCHEME);
|
||||
assertEquals("Authority is not equal", uri.getAuthority(), URIAUTHORITY);
|
||||
assertEquals("Host string is not equal", uri.getHost(), URIHOST);
|
||||
assertEquals("Path string is not equal", uri.getPath(), URIPATH);
|
||||
assertEquals("Port number is not equal", uri.getPort(), URIPORT);
|
||||
assertEquals("Query string is not equal", uri.getQuery(), URIQUERY);
|
||||
assertEquals("Fragment string is not equal", uri.getFragment(), URIFRAGMENT);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.javanetworking.url.test;
|
||||
package com.baeldung.javanetworking.uriurl.test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
@@ -18,11 +18,11 @@ import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.baeldung.javanetworking.url.URLDemo;
|
||||
import com.baeldung.javanetworking.uriurl.URLDemo;
|
||||
|
||||
@FixMethodOrder
|
||||
public class URLDemoTest {
|
||||
private final Logger log = LoggerFactory.getLogger(URLDemo.class);
|
||||
private final Logger log = LoggerFactory.getLogger(URLDemoTest.class);
|
||||
static String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||
// parsed locator
|
||||
static String URLPROTOCOL = "https";
|
||||
+3
-3
@@ -14,7 +14,7 @@ import org.hamcrest.collection.IsIterableContainingInOrder;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FlattenNestedListUnitTest {
|
||||
List<List<String>> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
|
||||
private List<List<String>> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
|
||||
|
||||
@Test
|
||||
public void givenNestedList_thenFlattenImperatively() {
|
||||
@@ -36,13 +36,13 @@ public class FlattenNestedListUnitTest {
|
||||
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
|
||||
}
|
||||
|
||||
public <T> List<T> flattenListOfListsImperatively(List<List<T>> list) {
|
||||
private <T> List<T> flattenListOfListsImperatively(List<List<T>> list) {
|
||||
List<T> ls = new ArrayList<>();
|
||||
list.forEach(ls::addAll);
|
||||
return ls;
|
||||
}
|
||||
|
||||
public <T> List<T> flattenListOfListsStream(List<List<T>> list) {
|
||||
private <T> List<T> flattenListOfListsStream(List<List<T>> list) {
|
||||
return list.stream().flatMap(Collection::stream).collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
package com.baeldung.list.listoflist;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ListOfListsUnitTest {
|
||||
|
||||
private List<ArrayList<? extends Stationery>> listOfLists = new ArrayList<ArrayList<? extends Stationery>>();
|
||||
private ArrayList<Pen> penList = new ArrayList<>();
|
||||
private ArrayList<Pencil> pencilList = new ArrayList<>();
|
||||
private ArrayList<Rubber> rubberList = new ArrayList<>();
|
||||
private List<List<? extends Stationery>> listOfLists = new ArrayList<>();
|
||||
private List<Pen> penList = new ArrayList<>();
|
||||
private List<Pencil> pencilList = new ArrayList<>();
|
||||
private List<Rubber> rubberList = new ArrayList<>();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Before
|
||||
@@ -29,11 +30,11 @@ public class ListOfListsUnitTest {
|
||||
@Test
|
||||
public void givenListOfLists_thenCheckNames() {
|
||||
assertEquals("Pen 1", ((Pen) listOfLists.get(0)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
assertEquals("Pencil 1", ((Pencil) listOfLists.get(1)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(2)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -43,10 +44,10 @@ public class ListOfListsUnitTest {
|
||||
((ArrayList<Pencil>) listOfLists.get(1)).remove(0);
|
||||
listOfLists.remove(1);
|
||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
listOfLists.remove(0);
|
||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -60,17 +61,17 @@ public class ListOfListsUnitTest {
|
||||
ArrayList<Rubber> rubbers = new ArrayList<>();
|
||||
rubbers.add(new Rubber("Rubber 1"));
|
||||
rubbers.add(new Rubber("Rubber 2"));
|
||||
|
||||
|
||||
List<ArrayList<? extends Stationery>> list = new ArrayList<ArrayList<? extends Stationery>>();
|
||||
list.add(pens);
|
||||
list.add(pencils);
|
||||
list.add(rubbers);
|
||||
|
||||
|
||||
assertEquals("Pen 1", ((Pen) list.get(0)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
assertEquals("Pencil 1", ((Pencil) list.get(1)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
assertEquals("Rubber 1", ((Rubber) list.get(2)
|
||||
.get(0)).getName());
|
||||
.get(0)).getName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ public class MappedByteBufferUnitTest {
|
||||
|
||||
//when
|
||||
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite,
|
||||
EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
|
||||
EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
|
||||
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
|
||||
|
||||
if (mappedByteBuffer != null) {
|
||||
@@ -61,7 +61,7 @@ public class MappedByteBufferUnitTest {
|
||||
|
||||
}
|
||||
|
||||
public Path getFileURIFromResources(String fileName) throws Exception {
|
||||
private Path getFileURIFromResources(String fileName) throws Exception {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
return Paths.get(classLoader.getResource(fileName).getPath());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
public class BigDecimalImplTest {
|
||||
|
||||
@Test
|
||||
public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
|
||||
BigDecimal serviceTax = new BigDecimal("56.0084578639");
|
||||
serviceTax = serviceTax.setScale(2, RoundingMode.CEILING);
|
||||
|
||||
BigDecimal entertainmentTax = new BigDecimal("23.00689");
|
||||
entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR);
|
||||
|
||||
BigDecimal totalTax = serviceTax.add(entertainmentTax);
|
||||
BigDecimal result = BigDecimal.valueOf(79.01);
|
||||
|
||||
Assert.assertEquals(result, totalTax);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class BigIntegerImplTest {
|
||||
|
||||
@Test
|
||||
public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() {
|
||||
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
|
||||
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
|
||||
|
||||
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
|
||||
BigInteger result = new BigInteger("14110718640342675608722521633212952");
|
||||
|
||||
Assert.assertEquals(result, totalStars);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import org.decimal4j.util.DoubleRounder;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
public class RoundTest {
|
||||
private double value = 2.03456d;
|
||||
private int places = 2;
|
||||
|
||||
@@ -3,13 +3,13 @@ package com.baeldung.money;
|
||||
import org.javamoney.moneta.FastMoney;
|
||||
import org.javamoney.moneta.Money;
|
||||
import org.javamoney.moneta.format.CurrencyStyle;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.money.CurrencyUnit;
|
||||
import javax.money.Monetary;
|
||||
import javax.money.MonetaryAmount;
|
||||
import javax.money.UnknownCurrencyException;
|
||||
import javax.money.convert.ConversionQueryBuilder;
|
||||
import javax.money.convert.CurrencyConversion;
|
||||
import javax.money.convert.MonetaryConversions;
|
||||
import javax.money.format.AmountFormatQueryBuilder;
|
||||
@@ -19,7 +19,11 @@ import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class JavaMoneyUnitTest {
|
||||
|
||||
@@ -36,17 +40,16 @@ public class JavaMoneyUnitTest {
|
||||
@Test(expected = UnknownCurrencyException.class)
|
||||
public void givenCurrencyCode_whenNoExist_thanThrowsError() {
|
||||
Monetary.getCurrency("AAA");
|
||||
fail(); // if no exception
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAmounts_whenStringified_thanEquals() {
|
||||
CurrencyUnit usd = Monetary.getCurrency("USD");
|
||||
MonetaryAmount fstAmtUSD = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency(usd)
|
||||
.setNumber(200)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency(usd)
|
||||
.setNumber(200)
|
||||
.create();
|
||||
Money moneyof = Money.of(12, usd);
|
||||
FastMoney fastmoneyof = FastMoney.of(2, usd);
|
||||
|
||||
@@ -59,10 +62,10 @@ public class JavaMoneyUnitTest {
|
||||
@Test
|
||||
public void givenCurrencies_whenCompared_thanNotequal() {
|
||||
MonetaryAmount oneDolar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
Money oneEuro = Money.of(1, "EUR");
|
||||
|
||||
assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
|
||||
@@ -72,10 +75,10 @@ public class JavaMoneyUnitTest {
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void givenAmount_whenDivided_thanThrowsException() {
|
||||
MonetaryAmount oneDolar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
oneDolar.divide(3);
|
||||
fail(); // if no exception
|
||||
}
|
||||
@@ -85,8 +88,8 @@ public class JavaMoneyUnitTest {
|
||||
List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
|
||||
|
||||
Money sumAmtCHF = (Money) monetaryAmounts
|
||||
.stream()
|
||||
.reduce(Money.of(0, "CHF"), MonetaryAmount::add);
|
||||
.stream()
|
||||
.reduce(Money.of(0, "CHF"), MonetaryAmount::add);
|
||||
|
||||
assertEquals("CHF 111.35", sumAmtCHF.toString());
|
||||
}
|
||||
@@ -97,18 +100,18 @@ public class JavaMoneyUnitTest {
|
||||
|
||||
Money moneyof = Money.of(12, usd);
|
||||
MonetaryAmount fstAmtUSD = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency(usd)
|
||||
.setNumber(200.50)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency(usd)
|
||||
.setNumber(200.50)
|
||||
.create();
|
||||
MonetaryAmount oneDolar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
Money subtractedAmount = Money
|
||||
.of(1, "USD")
|
||||
.subtract(fstAmtUSD);
|
||||
.of(1, "USD")
|
||||
.subtract(fstAmtUSD);
|
||||
MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
|
||||
MonetaryAmount divideAmount = oneDolar.divide(0.25);
|
||||
|
||||
@@ -124,22 +127,23 @@ public class JavaMoneyUnitTest {
|
||||
@Test
|
||||
public void givenAmount_whenRounded_thanEquals() {
|
||||
MonetaryAmount fstAmtEUR = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("EUR")
|
||||
.setNumber(1.30473908)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("EUR")
|
||||
.setNumber(1.30473908)
|
||||
.create();
|
||||
MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
|
||||
assertEquals("EUR 1.30473908", fstAmtEUR.toString());
|
||||
assertEquals("EUR 1.3", roundEUR.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore("Currency providers are not always available")
|
||||
public void givenAmount_whenConversion_thenNotNull() {
|
||||
MonetaryAmount oneDollar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
|
||||
CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
|
||||
|
||||
@@ -152,10 +156,10 @@ public class JavaMoneyUnitTest {
|
||||
@Test
|
||||
public void givenLocale_whenFormatted_thanEquals() {
|
||||
MonetaryAmount oneDollar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
|
||||
String usFormatted = formatUSD.format(oneDollar);
|
||||
|
||||
@@ -167,16 +171,16 @@ public class JavaMoneyUnitTest {
|
||||
@Test
|
||||
public void givenAmount_whenCustomFormat_thanEquals() {
|
||||
MonetaryAmount oneDollar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
|
||||
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
|
||||
.of(Locale.US)
|
||||
.set(CurrencyStyle.NAME)
|
||||
.set("pattern", "00000.00 ¤")
|
||||
.build());
|
||||
.of(Locale.US)
|
||||
.set(CurrencyStyle.NAME)
|
||||
.set("pattern", "00000.00 ¤")
|
||||
.build());
|
||||
String customFormatted = customFormat.format(oneDollar);
|
||||
|
||||
assertNotNull(customFormat);
|
||||
|
||||
+1
-1
@@ -9,4 +9,4 @@ public class NoClassDefFoundErrorTest {
|
||||
NoClassDefFoundErrorExample sample = new NoClassDefFoundErrorExample();
|
||||
sample.getClassWithInitErrors();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,71 +1,73 @@
|
||||
package com.baeldung.regexp;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.Test;
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class EscapingCharsTest {
|
||||
@Test
|
||||
public void givenRegexWithDot_whenMatchingStr_thenMatches() {
|
||||
String strInput = "foof";
|
||||
String strRegex = "foo.";
|
||||
|
||||
|
||||
assertEquals(true, strInput.matches(strRegex));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDotEsc_whenMatchingStr_thenNotMatching() {
|
||||
String strInput = "foof";
|
||||
String strRegex = "foo\\.";
|
||||
|
||||
|
||||
assertEquals(false, strInput.matches(strRegex));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRegexWithPipeEscaped_whenSplitStr_thenSplits() {
|
||||
String strInput = "foo|bar|hello|world";
|
||||
String strRegex = "\\Q|\\E";
|
||||
|
||||
|
||||
assertEquals(4, strInput.split(strRegex).length);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRegexWithPipeEscQuoteMeth_whenSplitStr_thenSplits() {
|
||||
String strInput = "foo|bar|hello|world";
|
||||
String strRegex = "|";
|
||||
|
||||
assertEquals(4,strInput.split(Pattern.quote(strRegex)).length);
|
||||
|
||||
assertEquals(4, strInput.split(Pattern.quote(strRegex)).length);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDollar_whenReplacing_thenNotReplace() {
|
||||
String strInput = "I gave $50 to my brother."
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
String strRegex = "$";
|
||||
String strReplacement = "£";
|
||||
String output = "I gave £50 to my brother."
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
Pattern p = Pattern.compile(strRegex);
|
||||
Matcher m = p.matcher(strInput);
|
||||
|
||||
|
||||
assertThat(output, not(equalTo(m.replaceAll(strReplacement))));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDollarEsc_whenReplacing_thenReplace() {
|
||||
String strInput = "I gave $50 to my brother."
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
String strRegex = "\\$";
|
||||
String strReplacement = "£";
|
||||
String output = "I gave £50 to my brother."
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
Pattern p = Pattern.compile(strRegex);
|
||||
Matcher m = p.matcher(strInput);
|
||||
|
||||
assertEquals(output,m.replaceAll(strReplacement));
|
||||
|
||||
assertEquals(output, m.replaceAll(strReplacement));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,11 @@ import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.script.*;
|
||||
import javax.script.Bindings;
|
||||
import javax.script.Invocable;
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptEngineManager;
|
||||
import javax.script.ScriptException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.baeldung.serialization;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
@@ -8,57 +8,57 @@ import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PersonUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
|
||||
Person p = new Person();
|
||||
p.setAge(20);
|
||||
p.setName("Joe");
|
||||
@Test
|
||||
public void whenSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
|
||||
Person p = new Person();
|
||||
p.setAge(20);
|
||||
p.setName("Joe");
|
||||
|
||||
FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
objectOutputStream.writeObject(p);
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
objectOutputStream.writeObject(p);
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
|
||||
FileInputStream fileInputStream = new FileInputStream("yofile.txt");
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
Person p2 = (Person) objectInputStream.readObject();
|
||||
objectInputStream.close();
|
||||
FileInputStream fileInputStream = new FileInputStream("yofile.txt");
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
Person p2 = (Person) objectInputStream.readObject();
|
||||
objectInputStream.close();
|
||||
|
||||
assertTrue(p2.getAge() == p.getAge());
|
||||
assertTrue(p2.getName().equals(p.getName()));
|
||||
}
|
||||
assertTrue(p2.getAge() == p.getAge());
|
||||
assertTrue(p2.getName().equals(p.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
|
||||
Person p = new Person();
|
||||
p.setAge(20);
|
||||
p.setName("Joe");
|
||||
@Test
|
||||
public void whenCustomSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
|
||||
Person p = new Person();
|
||||
p.setAge(20);
|
||||
p.setName("Joe");
|
||||
|
||||
Address a = new Address();
|
||||
a.setHouseNumber(1);
|
||||
Address a = new Address();
|
||||
a.setHouseNumber(1);
|
||||
|
||||
Employee e = new Employee();
|
||||
e.setPerson(p);
|
||||
e.setAddress(a);
|
||||
Employee e = new Employee();
|
||||
e.setPerson(p);
|
||||
e.setAddress(a);
|
||||
|
||||
FileOutputStream fileOutputStream = new FileOutputStream("yofile2.txt");
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
objectOutputStream.writeObject(e);
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
FileOutputStream fileOutputStream = new FileOutputStream("yofile2.txt");
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
objectOutputStream.writeObject(e);
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
|
||||
FileInputStream fileInputStream = new FileInputStream("yofile2.txt");
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
Employee e2 = (Employee) objectInputStream.readObject();
|
||||
objectInputStream.close();
|
||||
FileInputStream fileInputStream = new FileInputStream("yofile2.txt");
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
Employee e2 = (Employee) objectInputStream.readObject();
|
||||
objectInputStream.close();
|
||||
|
||||
assertTrue(e2.getPerson().getAge() == e.getPerson().getAge());
|
||||
assertTrue(e2.getAddress().getHouseNumber() == (e.getAddress().getHouseNumber()));
|
||||
}
|
||||
assertTrue(e2.getPerson().getAge() == e.getPerson().getAge());
|
||||
assertTrue(e2.getAddress().getHouseNumber() == (e.getAddress().getHouseNumber()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
package com.baeldung.socket;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class EchoIntegrationTest {
|
||||
private static final Integer PORT = 4444;
|
||||
|
||||
|
||||
+1
-2
@@ -1,11 +1,10 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
import static org.junit.Assert.fail;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CyclicDependancyManualTest {
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void whenInstanciatingClassOne_thenThrowsException() {
|
||||
ClassOne obj = new ClassOne();
|
||||
ClassOne obj = new ClassOne();
|
||||
}
|
||||
}
|
||||
|
||||
+5
-5
@@ -1,9 +1,9 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class InfiniteRecursionWithTerminationConditionManualTest {
|
||||
@Test
|
||||
public void givenPositiveIntNoOne_whenCalcFact_thenCorrectlyCalc() {
|
||||
@@ -23,9 +23,9 @@ public class InfiniteRecursionWithTerminationConditionManualTest {
|
||||
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void givenNegativeInt_whenCalcFact_thenThrowsException() {
|
||||
int numToCalcFactorial = -1;
|
||||
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
|
||||
int numToCalcFactorial = -1;
|
||||
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
|
||||
|
||||
irtc.calculateFactorial(numToCalcFactorial);
|
||||
irtc.calculateFactorial(numToCalcFactorial);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class RecursionWithCorrectTerminationConditionManualTest {
|
||||
@Test
|
||||
public void givenNegativeInt_whenCalcFact_thenCorrectlyCalc() {
|
||||
|
||||
+8
-8
@@ -6,25 +6,25 @@ import org.junit.Test;
|
||||
public class UnintendedInfiniteRecursionManualTest {
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void givenPositiveIntNoOne_whenCalFact_thenThrowsException() {
|
||||
int numToCalcFactorial= 1;
|
||||
int numToCalcFactorial = 1;
|
||||
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
|
||||
|
||||
|
||||
uir.calculateFactorial(numToCalcFactorial);
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void givenPositiveIntGtOne_whenCalcFact_thenThrowsException() {
|
||||
int numToCalcFactorial= 2;
|
||||
int numToCalcFactorial = 2;
|
||||
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
|
||||
|
||||
|
||||
uir.calculateFactorial(numToCalcFactorial);
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void givenNegativeInt_whenCalcFact_thenThrowsException() {
|
||||
int numToCalcFactorial= -1;
|
||||
int numToCalcFactorial = -1;
|
||||
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
|
||||
|
||||
|
||||
uir.calculateFactorial(numToCalcFactorial);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@ import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static com.baeldung.strategy.Discounter.*;
|
||||
import static com.baeldung.strategy.Discounter.christmas;
|
||||
import static com.baeldung.strategy.Discounter.easter;
|
||||
import static com.baeldung.strategy.Discounter.newYear;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StrategyDesignPatternUnitTest {
|
||||
@@ -26,7 +28,7 @@ public class StrategyDesignPatternUnitTest {
|
||||
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithAnonyousTypes() {
|
||||
Discounter staffDiscounter = new Discounter() {
|
||||
@Override
|
||||
public BigDecimal apply( BigDecimal amount) {
|
||||
public BigDecimal apply(BigDecimal amount) {
|
||||
return amount.multiply(BigDecimal.valueOf(0.5));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -5,7 +5,6 @@ import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -22,8 +21,8 @@ public class InfiniteStreamUnitTest {
|
||||
|
||||
//when
|
||||
List<Integer> collect = infiniteStream
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(collect, Arrays.asList(0, 2, 4, 6, 8, 10, 12, 14, 16, 18));
|
||||
@@ -37,9 +36,9 @@ public class InfiniteStreamUnitTest {
|
||||
|
||||
//when
|
||||
List<UUID> randomInts = infiniteStreamOfRandomUUID
|
||||
.skip(10)
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
.skip(10)
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(randomInts.size(), 10);
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamAddUnitTest {
|
||||
|
||||
@@ -25,7 +27,7 @@ public class StreamAddUnitTest {
|
||||
Stream<Integer> newStream = Stream.concat(Stream.of(99), anStream);
|
||||
|
||||
assertEquals(newStream.findFirst()
|
||||
.get(), (Integer) 99);
|
||||
.get(), (Integer) 99);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -38,7 +40,7 @@ public class StreamAddUnitTest {
|
||||
assertEquals(resultList.get(3), (Double) 9.9);
|
||||
}
|
||||
|
||||
public <T> Stream<T> insertInStream(Stream<T> stream, T elem, int index) {
|
||||
private <T> Stream<T> insertInStream(Stream<T> stream, T elem, int index) {
|
||||
List<T> result = stream.collect(Collectors.toList());
|
||||
result.add(index, elem);
|
||||
return result.stream();
|
||||
|
||||
@@ -20,13 +20,13 @@ public class StreamApiTest {
|
||||
|
||||
assertEquals("Sean", last);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenInfiniteStream_whenGetInfiniteStreamLastElementUsingReduce_thenReturnLastElement() {
|
||||
int last = StreamApi.getInfiniteStreamLastElementUsingReduce();
|
||||
assertEquals(19, last);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenListAndCount_whenGetLastElementUsingSkip_thenReturnLastElement() {
|
||||
List<String> valueList = new ArrayList<>();
|
||||
|
||||
@@ -1,68 +1,66 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.string.JoinerSplitter;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class JoinerSplitterUnitTest {
|
||||
|
||||
@Test
|
||||
public void provided_array_convert_to_stream_and_convert_to_string() {
|
||||
@Test
|
||||
public void provided_array_convert_to_stream_and_convert_to_string() {
|
||||
|
||||
String[] programming_languages = {"java", "python", "nodejs", "ruby"};
|
||||
String[] programming_languages = {"java", "python", "nodejs", "ruby"};
|
||||
|
||||
String expectation = "java,python,nodejs,ruby";
|
||||
|
||||
String result = JoinerSplitter.join(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_transformedToStream_convertToPrefixPostfixString() {
|
||||
String expectation = "java,python,nodejs,ruby";
|
||||
|
||||
String[] programming_languages = {"java", "python",
|
||||
"nodejs", "ruby"};
|
||||
String expectation = "[java,python,nodejs,ruby]";
|
||||
|
||||
String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToList() {
|
||||
String result = JoinerSplitter.join(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<String> expectation = new ArrayList<String>();
|
||||
expectation.add("java");
|
||||
expectation.add("python");
|
||||
expectation.add("nodejs");
|
||||
expectation.add("ruby");
|
||||
|
||||
List<String> result = JoinerSplitter.split(programming_languages);
|
||||
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToListOfChar() {
|
||||
@Test
|
||||
public void givenArray_transformedToStream_convertToPrefixPostfixString() {
|
||||
|
||||
String[] programming_languages = {"java", "python",
|
||||
"nodejs", "ruby"};
|
||||
String expectation = "[java,python,nodejs,ruby]";
|
||||
|
||||
String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToList() {
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<String> expectation = new ArrayList<String>();
|
||||
expectation.add("java");
|
||||
expectation.add("python");
|
||||
expectation.add("nodejs");
|
||||
expectation.add("ruby");
|
||||
|
||||
List<String> result = JoinerSplitter.split(programming_languages);
|
||||
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToListOfChar() {
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<Character> expectation = new ArrayList<Character>();
|
||||
char[] charArray = programming_languages.toCharArray();
|
||||
for (char c : charArray) {
|
||||
expectation.add(c);
|
||||
}
|
||||
|
||||
List<Character> result = JoinerSplitter.splitToListOfChar(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
|
||||
}
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<Character> expectation = new ArrayList<Character>();
|
||||
char[] charArray = programming_languages.toCharArray();
|
||||
for (char c : charArray) {
|
||||
expectation.add(c);
|
||||
}
|
||||
|
||||
List<Character> result = JoinerSplitter.splitToListOfChar(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.baeldung.string;
|
||||
|
||||
import com.google.common.base.Splitter;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.assertj.core.util.Lists;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringHelperUnitTest {
|
||||
|
||||
@@ -67,7 +68,7 @@ public class StringHelperUnitTest {
|
||||
assertEquals("abc", StringHelper.removeLastCharOptional(WHITE_SPACE_AT_THE_END_STRING));
|
||||
assertEquals("abc", StringHelper.removeLastCharRegexOptional(WHITE_SPACE_AT_THE_END_STRING));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenStringWithNewLineAtTheEnd_whenSubstring_thenGetStringWithoutNewLine() {
|
||||
assertEquals("abc", StringHelper.removeLastChar(NEW_LINE_AT_THE_END_STRING));
|
||||
@@ -78,7 +79,7 @@ public class StringHelperUnitTest {
|
||||
assertEquals("abc", StringHelper.removeLastCharOptional(NEW_LINE_AT_THE_END_STRING));
|
||||
assertNotEquals("abc", StringHelper.removeLastCharRegexOptional(NEW_LINE_AT_THE_END_STRING));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenMultiLineString_whenSubstring_thenGetStringWithoutNewLine() {
|
||||
assertEquals("abc\nde", StringHelper.removeLastChar(MULTIPLE_LINES_STRING));
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.typeerasure;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class TypeErasureUnitTest {
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void givenIntegerStack_whenStringPushedAndAssignPoppedValueToInteger_shouldFail() {
|
||||
IntegerStack integerStack = new IntegerStack(5);
|
||||
Stack stack = integerStack;
|
||||
stack.push("Hello");
|
||||
Integer data = integerStack.pop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnyArray_whenInvokedPrintArray_shouldSucceed() {
|
||||
Integer[] scores = new Integer[] { 100, 200, 10, 99, 20 };
|
||||
ArrayContentPrintUtil.printArray(scores);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -15,7 +15,7 @@ class OffHeapArray {
|
||||
return (Unsafe) f.get(null);
|
||||
}
|
||||
|
||||
public OffHeapArray(long size) throws NoSuchFieldException, IllegalAccessException {
|
||||
OffHeapArray(long size) throws NoSuchFieldException, IllegalAccessException {
|
||||
this.size = size;
|
||||
address = getUnsafe().allocateMemory(size * BYTE);
|
||||
}
|
||||
@@ -32,7 +32,7 @@ class OffHeapArray {
|
||||
return size;
|
||||
}
|
||||
|
||||
public void freeMemory() throws NoSuchFieldException, IllegalAccessException {
|
||||
void freeMemory() throws NoSuchFieldException, IllegalAccessException {
|
||||
getUnsafe().freeMemory(address);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user