From 460eb93a27e289f4782a1b645555909ce59498c7 Mon Sep 17 00:00:00 2001 From: Ayman Nedjmeddine Date: Fri, 9 Jan 2015 09:37:23 +0100 Subject: [PATCH 01/21] Did a first code inspection tour Corrected some typos Emptied some auto-generated catch sections and renamed the exception variable to "ignored" --- .../CallableAndFuture_13/CallableTester.java | 2 +- .../src/CountDownLatch_6/App.java | 7 ++----- .../src/Deadlock_11/Runner.java | 2 +- .../src/Deadlock_11/SimpleDeadLock.java | 8 ++++---- .../src/InterruptingThreads14/App.java | 10 +++++----- .../Worker.java | 5 +---- .../src/LockObjects_4/Worker.java | 8 ++++---- .../WorkerMethodsSynchronized.java | 9 +++------ .../LowLevelProducerConsumer_9/Processor.java | 4 ++-- .../src/Semaphores_12/App.java | 2 +- .../src/Semaphores_12/Connection.java | 8 ++++---- .../ApplicationAnonymous.java | 5 +---- .../src/ThreadPools_5/App.java | 4 ++-- .../src/ThreadPools_5/WorkerThreadPool.java | 20 +++++++++---------- 14 files changed, 41 insertions(+), 53 deletions(-) diff --git a/JavaMultiThreadingCodes/src/CallableAndFuture_13/CallableTester.java b/JavaMultiThreadingCodes/src/CallableAndFuture_13/CallableTester.java index 29c75aa..8fd3511 100644 --- a/JavaMultiThreadingCodes/src/CallableAndFuture_13/CallableTester.java +++ b/JavaMultiThreadingCodes/src/CallableAndFuture_13/CallableTester.java @@ -18,7 +18,7 @@ * Runnable Introduced in Java 1.0 Callable Introduced in Java 1.5 as part of * java.util.concurrent library * - * Runnable cannot be parameterized Callable is a parameterized type whose type + * Runnable cannot be parametrized Callable is a parametrized type whose type * parameter indicates the return type of its run method Classes implementing * * Runnable needs to implement run() method, classes implementing Callable needs diff --git a/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java b/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java index 646efe7..1447d2f 100644 --- a/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java +++ b/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java @@ -45,10 +45,7 @@ public void run() { try { Thread.sleep(3000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} latch.countDown(); } } @@ -62,7 +59,7 @@ public static void main(String[] args) { executor.submit(new Processor(latch)); } try { - // Application’s main thread waits, till other service threads which are + // Application’s main thread waits, till other service threads which are // as an example responsible for starting framework services have completed started all services. latch.await(); } catch (InterruptedException e) { diff --git a/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java b/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java index f293f41..970d502 100644 --- a/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java +++ b/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java @@ -53,7 +53,7 @@ private void acquireLocks(Lock firstLock, Lock secondLock) throws InterruptedExc } } - //firstThreaad runs + //firstThread runs public void firstThread() throws InterruptedException { Random random = new Random(); for (int i = 0; i < 10000; i++) { diff --git a/JavaMultiThreadingCodes/src/Deadlock_11/SimpleDeadLock.java b/JavaMultiThreadingCodes/src/Deadlock_11/SimpleDeadLock.java index 47f769a..10a9594 100644 --- a/JavaMultiThreadingCodes/src/Deadlock_11/SimpleDeadLock.java +++ b/JavaMultiThreadingCodes/src/Deadlock_11/SimpleDeadLock.java @@ -10,8 +10,8 @@ */ public class SimpleDeadLock { - public static Object lock1 = new Object(); - public static Object lock2 = new Object(); + public static final Object lock1 = new Object(); + public static final Object lock2 = new Object(); private int index; public static void main(String[] a) { @@ -28,7 +28,7 @@ public void run() { System.out.println("Thread 1: Holding lock 1..."); try { Thread.sleep(10); - } catch (InterruptedException e) { + } catch (InterruptedException ignored) { } System.out.println("Thread 1: Waiting for lock 2..."); synchronized (lock2) { @@ -45,7 +45,7 @@ public void run() { System.out.println("Thread 2: Holding lock 2..."); try { Thread.sleep(10); - } catch (InterruptedException e) { + } catch (InterruptedException ignored) { } System.out.println("Thread 2: Waiting for lock 1..."); synchronized (lock1) { diff --git a/JavaMultiThreadingCodes/src/InterruptingThreads14/App.java b/JavaMultiThreadingCodes/src/InterruptingThreads14/App.java index f36769c..165a460 100644 --- a/JavaMultiThreadingCodes/src/InterruptingThreads14/App.java +++ b/JavaMultiThreadingCodes/src/InterruptingThreads14/App.java @@ -31,9 +31,9 @@ public static void main(String[] args) throws InterruptedException { System.out.println("Starting."); - ExecutorService executer = Executors.newCachedThreadPool(); + ExecutorService executor = Executors.newCachedThreadPool(); - Future fu = executer.submit(new Callable() { + Future fu = executor.submit(new Callable() { @Override public Void call() throws Exception { @@ -49,11 +49,11 @@ public Void call() throws Exception { } }); - executer.shutdown(); + executor.shutdown(); Thread.sleep(500); - executer.shutdownNow(); + executor.shutdownNow(); - executer.awaitTermination(1, TimeUnit.DAYS); + executor.awaitTermination(1, TimeUnit.DAYS); System.out.println("Finished."); } diff --git a/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java b/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java index d2bb0c3..b9c2a10 100644 --- a/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java +++ b/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java @@ -70,10 +70,7 @@ public void run() { try { thread1.join(); thread2.join(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} System.out.println("Count is: " + count); } } diff --git a/JavaMultiThreadingCodes/src/LockObjects_4/Worker.java b/JavaMultiThreadingCodes/src/LockObjects_4/Worker.java index ae381bb..fd5d7a7 100644 --- a/JavaMultiThreadingCodes/src/LockObjects_4/Worker.java +++ b/JavaMultiThreadingCodes/src/LockObjects_4/Worker.java @@ -21,11 +21,11 @@ public class Worker { private Random random = new Random(); - private Object lock1 = new Object(); - private Object lock2 = new Object(); + private final Object lock1 = new Object(); + private final Object lock2 = new Object(); - private List list1 = new ArrayList(); - private List list2 = new ArrayList(); + private List list1 = new ArrayList<>(); + private List list2 = new ArrayList<>(); public void stageOne() { diff --git a/JavaMultiThreadingCodes/src/LockObjects_4/WorkerMethodsSynchronized.java b/JavaMultiThreadingCodes/src/LockObjects_4/WorkerMethodsSynchronized.java index 5b7ac30..d122f57 100644 --- a/JavaMultiThreadingCodes/src/LockObjects_4/WorkerMethodsSynchronized.java +++ b/JavaMultiThreadingCodes/src/LockObjects_4/WorkerMethodsSynchronized.java @@ -21,8 +21,8 @@ public class WorkerMethodsSynchronized { private Random random = new Random(); - private List list1 = new ArrayList(); - private List list2 = new ArrayList(); + private List list1 = new ArrayList<>(); + private List list2 = new ArrayList<>(); /** * synchronized, methods use different data (list1 list2) so by synchronized @@ -78,10 +78,7 @@ public void run() { try { t1.join(); t2.join(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} long end = System.currentTimeMillis(); diff --git a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java b/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java index a93ba04..9e2be4d 100644 --- a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java +++ b/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java @@ -14,13 +14,13 @@ public class Processor { private LinkedList list = new LinkedList<>(); private final int LIMIT = 10; - private Object lock = new Object(); + private final Object lock = new Object(); public void produce() throws InterruptedException { int value = 0; while (true) { synchronized (lock) { - //whenever the threade is notofied starts again from the loop + //whenever the thread is notified starts again from the loop while (list.size() == LIMIT) { lock.wait();// wait() is also true } diff --git a/JavaMultiThreadingCodes/src/Semaphores_12/App.java b/JavaMultiThreadingCodes/src/Semaphores_12/App.java index dcccb55..6c1790b 100644 --- a/JavaMultiThreadingCodes/src/Semaphores_12/App.java +++ b/JavaMultiThreadingCodes/src/Semaphores_12/App.java @@ -40,7 +40,7 @@ public class App { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newCachedThreadPool(); - for (int i = 0; i < 13; i++) { //200 hundred times will be calleds + for (int i = 0; i < 13; i++) { //200 hundred times will be called executor.submit(new Runnable() { public void run() { Connection.getInstance().connect(); diff --git a/JavaMultiThreadingCodes/src/Semaphores_12/Connection.java b/JavaMultiThreadingCodes/src/Semaphores_12/Connection.java index f8f22c8..b4c77d7 100644 --- a/JavaMultiThreadingCodes/src/Semaphores_12/Connection.java +++ b/JavaMultiThreadingCodes/src/Semaphores_12/Connection.java @@ -15,8 +15,8 @@ public class Connection { private static Connection instance = new Connection(); //limit connections to 10 - //true means whichever the thread call the acquire first gets it first, - //in queue placed firts to obtain the permit. + //true means whichever the thread call the acquire first gets it first, + //in queue placed first to obtain the permit. private Semaphore sem = new Semaphore(10, true); private int connections = 0; @@ -34,7 +34,7 @@ public void connect() { e1.printStackTrace(); } try { - //if doConnect throws and exception is still releases the permit + //if doConnect throws and exception is still releases the permit //so we use a separate method here to increase the connections count. doConnect(); } finally { @@ -55,7 +55,7 @@ public void doConnect() { e.printStackTrace(); } //when exit doConnect method decrement number of connections - synchronized (this) {//atamoic + synchronized (this) {//atomic connections--; System.out.println("I'm done " + Thread.currentThread().getName() + " Connection is released , connection count: " + connections); } diff --git a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java index cd99566..f5e1210 100644 --- a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java +++ b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java @@ -20,10 +20,7 @@ public void run() { try { Thread.sleep(100); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} } } }); diff --git a/JavaMultiThreadingCodes/src/ThreadPools_5/App.java b/JavaMultiThreadingCodes/src/ThreadPools_5/App.java index c94b1c6..e447716 100644 --- a/JavaMultiThreadingCodes/src/ThreadPools_5/App.java +++ b/JavaMultiThreadingCodes/src/ThreadPools_5/App.java @@ -25,7 +25,7 @@ public void run() { System.out.println("Starting: " + id); try { Thread.sleep(5000); - } catch (InterruptedException e) { + } catch (InterruptedException ignored) { } System.out.println("Completed: " + id); } @@ -45,7 +45,7 @@ public static void main(String[] args) { System.out.println("All tasks submitted."); try { executor.awaitTermination(1, TimeUnit.DAYS); - } catch (InterruptedException e) { + } catch (InterruptedException ignored) { } System.out.println("All tasks completed."); } diff --git a/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java b/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java index 1535f50..ce72a01 100644 --- a/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java +++ b/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java @@ -19,8 +19,8 @@ class Worker implements Runnable { private Random random = new Random(); - private Object lock1 = new Object(); - private Object lock2 = new Object(); + private final Object lock1 = new Object(); + private final Object lock2 = new Object(); public List list1 = new ArrayList<>(); public List list2 = new ArrayList<>(); @@ -64,21 +64,21 @@ public void stageTwo() { public class WorkerThreadPool { public static void main(String[] args) { - ExecutorService executer = Executors.newFixedThreadPool(2);//two threads, try setting by 1 to observe time + ExecutorService executor = Executors.newFixedThreadPool(2);//two threads, try setting by 1 to observe time System.out.println("Starting ..."); long start = System.currentTimeMillis(); Worker worker = new Worker(); for (int i = 0; i < 2; i++) {//worker.run is called 2 (threads started) times by two threads - executer.submit(worker); + executor.submit(worker); } - executer.shutdown(); //prevents new tasks from being accepted by the ExecutorService + executor.shutdown(); //prevents new tasks from being accepted by the ExecutorService try { - executer.awaitTermination(1, TimeUnit.DAYS); - // How long should I wait for termination If I donot know exactly when threads are done with the tasks ? + executor.awaitTermination(1, TimeUnit.DAYS); + // How long should I wait for termination If I do not know exactly when threads are done with the tasks ? // Source:http://stackoverflow.com/questions/1250643/how-to-wait-for-all-threads-to-finish-using-executorservice - // For a perpetually running batch kind of thing u need to submit jobs and wait for them to - // finish before jumping ahead. - // In Such a case a latch or a barrier makes more sense than a shutdown (see CountDownLatch_6.App). + // For a perpetually running batch kind of thing u need to submit jobs and wait for them to + // finish before jumping ahead. + // In Such a case a latch or a barrier makes more sense than a shutdown (see CountDownLatch_6.App). } catch (InterruptedException ex) { System.out.println(ex.getMessage()); } From 8ed7488d2d0d1677b9341ca56cac0c6197433e1c Mon Sep 17 00:00:00 2001 From: Ayman Nedjmeddine Date: Fri, 9 Jan 2015 09:43:20 +0100 Subject: [PATCH 02/21] In the CountDownLatch_6.App#App ; the thread pool must be shut down ... Otherwise the app (main thread) wont stop executing after the last line. --- JavaMultiThreadingCodes/src/CountDownLatch_6/App.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java b/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java index 1447d2f..7b4c734 100644 --- a/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java +++ b/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java @@ -58,6 +58,8 @@ public static void main(String[] args) { for (int i = 0; i < 3; i++) { executor.submit(new Processor(latch)); } + executor.shutdown(); + try { // Application’s main thread waits, till other service threads which are // as an example responsible for starting framework services have completed started all services. From b531a8a292410a4cbc264d700e80acf5aadd01a7 Mon Sep 17 00:00:00 2001 From: IOAyman Date: Fri, 9 Jan 2015 10:42:53 +0100 Subject: [PATCH 03/21] CountDownLatch_7.App#App Clean up auto-generated catch blocks re-activated the 0.1sec pause in consumer() (for the sake of not flooding the output terminal) Commented out {t1,t2}.join() ... instead, forced the app (main thread) to quite after 30secs --- .../src/ProducerConsumer_7/App.java | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java b/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java index 7440082..9416f76 100644 --- a/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java +++ b/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java @@ -32,16 +32,12 @@ public class App { private static BlockingQueue queue = new ArrayBlockingQueue<>(10); public static void main(String[] args) throws InterruptedException { - /** - * - */ + Thread t1 = new Thread(new Runnable() { public void run() { try { producer(); - } catch (InterruptedException e) { - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} } }); @@ -49,16 +45,17 @@ public void run() { public void run() { try { consumer(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} } }); t1.start(); t2.start(); - t1.join(); - t2.join(); +// t1.join(); +// t2.join(); + + // Pause for 30 seconds and force quitting the app (because we're looping infinitely) + Thread.sleep(30000); + System.exit(0); } private static void producer() throws InterruptedException { @@ -71,7 +68,7 @@ private static void producer() throws InterruptedException { private static void consumer() throws InterruptedException { Random random = new Random(); while (true) { - //Thread.sleep(100); + Thread.sleep(100); if (random.nextInt(10) == 0) { Integer value = queue.take();//if queue is empty waits System.out.println("Taken value: " + value + "; Queue size is: " + queue.size()); From b65b85e19c4bdd2db045909b2a9fc19c96f54376 Mon Sep 17 00:00:00 2001 From: IOAyman Date: Fri, 9 Jan 2015 12:21:55 +0100 Subject: [PATCH 04/21] Went back and optimized the JavaDoc for all the packages up till the 8th one (breaks, italics, class/package references ..etc), so it looks prettier when integrated to the IDE. --- .../src/CountDownLatch_6/App.java | 38 ++++++++------- .../Worker.java | 8 ++-- .../src/LockObjects_4/App.java | 4 +- .../src/ProducerConsumer_7/App.java | 22 +++++---- .../ApplicationAnonymous.java | 6 +-- .../StartingThreads_1/ApplicationExtends.java | 7 ++- .../ApplicationRunnable.java | 7 ++- .../src/ThreadPools_5/App.java | 6 +-- .../src/ThreadPools_5/WorkerThreadPool.java | 8 ++-- .../src/VolatileKeyword_2/App.java | 10 ++-- .../src/WaitAndNotify_8/BlockingQueueApp.java | 48 +++++++++++-------- .../src/WaitAndNotify_8/Processor.java | 4 +- 12 files changed, 91 insertions(+), 77 deletions(-) diff --git a/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java b/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java index 7b4c734..20164d7 100644 --- a/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java +++ b/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java @@ -5,30 +5,34 @@ import java.util.concurrent.Executors; /** - * CountDownLatch Java class to synchronize your threads’ activities. - * + * {@link java.util.concurrent.CountDownLatch} Java class to synchronize your threads’ activities. + *

* Source: - * (http://stackoverflow.com/questions/17827022/what-is-countdown-latch-in-java-multithreading) + * http://stackoverflow.com/questions/17827022/what-is-countdown-latch-in-java-multithreading
+ * * Any thread, usually main thread of application, which calls - * CountDownLatch.await() will wait until count reaches zero or its interrupted + * {@link java.util.concurrent.CountDownLatch#await()} will wait until count reaches zero or its interrupted * by another thread. All other thread are required to do count down by calling - * CountDownLatch.countDown() once they are completed or ready. - * + * {@link java.util.concurrent.CountDownLatch#countDown()} once they are completed or ready. + *
* As soon as count reaches zero, Thread awaiting starts running. One of the - * disadvantage of CountDownLatch is that its not reusable once count reaches to - * zero you can not use CountDownLatch any more. - * - * Use CountDownLatch when one thread like main thread, require to wait for one - * or more thread to complete, before it can start processing. - * - * Classical example of using CountDownLatch in Java is any server side core - * Java application which uses services architecture, where multiple services + * disadvantage of {@link java.util.concurrent.CountDownLatch} is that it's + * not reusable once the count reaches to + * zero you can not use {@link java.util.concurrent.CountDownLatch} any more. + *

+ * Use {@link java.util.concurrent.CountDownLatch} when one thread, like main + * thread, require to wait for one or more threads to complete, before it can + * start processing. + *

+ * Classical example of using {@link java.util.concurrent.CountDownLatch} in + * Java is any server side core Java application which uses services + * architecture, where multiple services * are provided by multiple threads and application can not start processing * until all services have started successfully. - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java b/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java index b9c2a10..a419f3c 100644 --- a/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java +++ b/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java @@ -4,12 +4,12 @@ import java.util.logging.Logger; /** - * synchronized ("only let one thread in here at a time".) and join ("wait until + * {@code synchronized} ("only let one thread in here at a time".) and {@code join} ("wait until * thread on which join has called finished") keyword. - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/LockObjects_4/App.java b/JavaMultiThreadingCodes/src/LockObjects_4/App.java index 96b6a13..e98d96f 100644 --- a/JavaMultiThreadingCodes/src/LockObjects_4/App.java +++ b/JavaMultiThreadingCodes/src/LockObjects_4/App.java @@ -1,9 +1,9 @@ package LockObjects_4; /** - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java b/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java index 9416f76..fa7b6be 100644 --- a/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java +++ b/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java @@ -1,14 +1,16 @@ package ProducerConsumer_7; /** - * producer-consumer pattern in Java using the ArrayBlockingQueue Java class. + * Producer-Consumer pattern in Java using the {@link java.util.concurrent + * .ArrayBlockingQueue} Java class. + *

* Producer-Consumer is the situation where one or more threads are producing * data items and adding them to a shared data store of some kind while one or * more other threads process those items, removing them from the data store. - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ @@ -19,14 +21,16 @@ public class App { /** - * Thread safe implementation of Queue data structure so you do not need to - * worry about synchronization. More specifically BlockingQueue + * Thread safe implementation of {@link java.util.Queue} data structure so + * you do not need to worry about synchronization. + * More specifically {@link java.util.concurrent.BlockingQueue} * implementations are thread-safe. All queuing methods are atomic in nature * and use internal locks or other forms of concurrency control. If * BlockingQueue is not used queue is shared data structure either - * sychronized or wait() notify() (see Course 8) should be used. Java 1.5 - * introduced a new concurrency library (in the java.util.concurrent - * package) which was designed to provide a higher level abstraction over + * {@code synchronized} or {@code wait() notify()} (see Course 8) should be + * used. + * Java 1.5 introduced a new concurrency library {@link java.util.concurrent} + * which was designed to provide a higher level abstraction over * the wait/notify mechanism. */ private static BlockingQueue queue = new ArrayBlockingQueue<>(10); diff --git a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java index f5e1210..fd61eb2 100644 --- a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java +++ b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java @@ -2,10 +2,10 @@ /** * Starting threads using the Thread constructor with anonymous classes - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationExtends.java b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationExtends.java index fbbac2e..e966135 100644 --- a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationExtends.java +++ b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationExtends.java @@ -2,10 +2,9 @@ /** * Starting Threads with extends - * - * Codes with minor comments are from - * http://www.caveofprogramming.com/youtube/ also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * also freely available at https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationRunnable.java b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationRunnable.java index 5d5237a..768cfc3 100644 --- a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationRunnable.java +++ b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationRunnable.java @@ -2,10 +2,9 @@ /** * Starting Threads using Runnable Interface - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ - * also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * also freely available at: https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/ThreadPools_5/App.java b/JavaMultiThreadingCodes/src/ThreadPools_5/App.java index e447716..649ea6c 100644 --- a/JavaMultiThreadingCodes/src/ThreadPools_5/App.java +++ b/JavaMultiThreadingCodes/src/ThreadPools_5/App.java @@ -2,10 +2,10 @@ /** * ThreadPool ("number of workers in a factory") - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java b/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java index ce72a01..5da9ee5 100644 --- a/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java +++ b/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java @@ -8,11 +8,11 @@ import java.util.concurrent.TimeUnit; /** - * This is the implementation of LockObjects_4.Worker with threadPool - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + * This is the implementation of {@link LockObjects_4.Worker} with threadPool + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/VolatileKeyword_2/App.java b/JavaMultiThreadingCodes/src/VolatileKeyword_2/App.java index cc9ba8e..c133425 100644 --- a/JavaMultiThreadingCodes/src/VolatileKeyword_2/App.java +++ b/JavaMultiThreadingCodes/src/VolatileKeyword_2/App.java @@ -1,12 +1,12 @@ package VolatileKeyword_2; /** - * Volatile Keyword, “… the volatile modifier guarantees that any thread that - * reads a field will see the most recently written value.” - Josh Bloch - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + * Volatile Keyword, “… the volatile modifier guarantees that any thread that + * reads a field will see the most recently written value.” - Josh Bloch + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java b/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java index 23c61d8..701d0d8 100644 --- a/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java +++ b/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java @@ -9,34 +9,40 @@ /** * Source: - * http://stackoverflow.com/questions/2536692/a-simple-scenario-using-wait-and-notify-in-java - * Firstly, you need to ensure that any calls to wait() or notify() are within a - * synchronized region of code (with the wait() and notify() calls being - * synchronized on the "same" object). The reason for this (other than the - * standard thread safety concerns) is due to something known as a missed - * signal. - * - * An example of this, is that a thread may call put() when the queue happens to - * be full, it then checks the condition, sees that the queue is full, however + * http://stackoverflow.com/questions/2536692/a-simple-scenario-using-wait-and-notify-in-java + *

+ * Firstly, you need to ensure that any calls to {@code wait() or notify()} are + * within a synchronized region of code (with the {@code wait() or notify()} + * calls being synchronized on the "same" object). + * The reason for this (other than the standard thread safety concerns) is + * due to something known as a missed signal. + *

+ * An example of this, is that a thread may call {@link WaitAndNotify_8.BlockingQueue#put} + * when the queue happens to be full, it then checks the condition, sees that + * the queue is full, however * before it can block another thread is scheduled. This second thread then - * take()'s an element from the queue, and notifies the waiting threads that the + * {@link WaitAndNotify_8.BlockingQueue#take()}'s an element from the queue, + * and notifies the waiting threads that the * queue is no longer full. Because the first thread has already checked the - * condition however, it will simply call wait() after being re-scheduled, even - * though it could make progress. - * + * condition. However, it will simply call {@code wait()} after being + * re-scheduled, even though it could make progress. + *
* By synchronizing on a shared object, you can ensure that this problem does - * not occur, as the second thread's take() call will not be able to make - * progress until the first thread has actually blocked. - * + * not occur,as the second thread's {@link WaitAndNotify_8.BlockingQueue#take()} + * call will not be able to make progress until the first thread has actually + * blocked. + *
* You must hold the lock (synchronized) before invoking wait/notify. Threads * also have to acquire lock before waking. - * - * More:In order to wait on an object, we must be synchronized on that object. + *

+ * More: In order to wait on an object, we must be synchronized on that object. + *
* But our thread will automatically release the lock temporarily while waiting. - * Calling wait() means that our thread will be suspended until it is + * Calling {@code wait()} means that our thread will be suspended until it is * "notified". Our thread will be "notified", and thus woken up, when another - * thread calls notify() on the object that we're waiting on (in this case, the - * connection list). When our thread wakes up, it automatically regains the + * thread calls {@code notify()} on the object that we're waiting on (in this + * case, the connection list). + * When our thread wakes up, it automatically regains the * lock. We can now check again that the list is not empty, and if it isn't, * safely take out the first connection. This checking and removing will be * atomic because we have the lock on the list. diff --git a/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java b/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java index bf4ca1a..2c4f7e7 100644 --- a/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java +++ b/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java @@ -26,7 +26,8 @@ public class Processor { /** * public synchronized void getSomething(){ this.hello = "hello World"; } * public void getSomething(){ synchronized(this){ this.hello = "hello - * World"; } , two code blocks by specification, functionally identical. + * World"; } } + * two code blocks by specification, functionally identical. */ public void produce() throws InterruptedException { synchronized (this) { @@ -45,6 +46,7 @@ public void consume() throws InterruptedException { System.out.println("Return key pressed."); notify(); Thread.sleep(5000); + System.out.println("Consumption done."); } } } From 52628e5594f9fa1054980a39ead205d80c352413 Mon Sep 17 00:00:00 2001 From: IOAyman Date: Sun, 11 Jan 2015 17:56:56 +0100 Subject: [PATCH 05/21] JavaDoc optimized for packages 7.8.9 Suppress inspection Warnings about infinite loop statements --- .../src/LowLevelProducerConsumer_9/App.java | 29 +++++++------- .../LowLevelProducerConsumer_9/Processor.java | 5 ++- .../src/ProducerConsumer_7/App.java | 4 +- .../src/WaitAndNotify_8/App.java | 16 ++++---- .../src/WaitAndNotify_8/BlockingQueueApp.java | 9 ++--- .../src/WaitAndNotify_8/Processor.java | 38 ++++++++++++------- 6 files changed, 56 insertions(+), 45 deletions(-) diff --git a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/App.java b/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/App.java index 99eb416..3e62cf3 100644 --- a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/App.java +++ b/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/App.java @@ -1,15 +1,16 @@ package LowLevelProducerConsumer_9; /** - * How to implement the producer-consumer pattern using "low level" techniques; + * How to implement the Producer-Consumer pattern using "low level" techniques; * namely, wait, notify and synchronized. This isn't the best way to implement a - * producer-consumer pattern in Java (see tutorial 7 use of BlockingQueue for + * Producer-Consumer pattern in Java + * (see tutorial 7 use of {@link java.util.concurrent.BlockingQueue} for * the best way); but this tutorial will help you to understand how to use wait * and notify. - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ @@ -22,9 +23,7 @@ public static void main(String[] args) throws InterruptedException { public void run() { try { processor.produce(); - } catch (InterruptedException e) { - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} } }); @@ -33,14 +32,18 @@ public void run() { public void run() { try { processor.consume(); - } catch (InterruptedException e) { - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} } }); + t1.start(); t2.start(); - t1.join(); - t2.join(); +// t1.join(); +// t2.join(); + + // Pause for 30 seconds and force quitting the app (because we're + // looping infinitely) + Thread.sleep(30000); + System.exit(0); } } diff --git a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java b/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java index 9e2be4d..e9f5a1d 100644 --- a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java +++ b/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java @@ -1,15 +1,16 @@ package LowLevelProducerConsumer_9; /** - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ import java.util.LinkedList; import java.util.Random; +@SuppressWarnings("InfiniteLoopStatement") public class Processor { private LinkedList list = new LinkedList<>(); diff --git a/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java b/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java index fa7b6be..1f62f46 100644 --- a/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java +++ b/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java @@ -18,6 +18,7 @@ import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; +@SuppressWarnings("InfiniteLoopStatement") public class App { /** @@ -57,7 +58,8 @@ public void run() { // t1.join(); // t2.join(); - // Pause for 30 seconds and force quitting the app (because we're looping infinitely) + // Pause for 30 seconds and force quitting the app (because we're + // looping infinitely) Thread.sleep(30000); System.exit(0); } diff --git a/JavaMultiThreadingCodes/src/WaitAndNotify_8/App.java b/JavaMultiThreadingCodes/src/WaitAndNotify_8/App.java index 4cc108e..f45c252 100644 --- a/JavaMultiThreadingCodes/src/WaitAndNotify_8/App.java +++ b/JavaMultiThreadingCodes/src/WaitAndNotify_8/App.java @@ -1,14 +1,15 @@ package WaitAndNotify_8; /** - * wait and notify in Java; low-level multithreading methods of the Object class + * {@link Object#wait()} and {@link Object#notify()} in Java; low-level + * multi-threading methods of the {@link java.lang.Object} class * that allow you to have one or more threads sleeping, only to be woken up by * other threads at the right moment. Extremely useful for avoiding those * processor-consuming "polling loops". * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ @@ -21,9 +22,7 @@ public static void main(String[] args) throws InterruptedException { public void run() { try { processor.produce(); - } catch (InterruptedException e) { - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} } }); @@ -32,11 +31,10 @@ public void run() { public void run() { try { processor.consume(); - } catch (InterruptedException e) { - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} } }); + t1.start(); t2.start(); t1.join(); diff --git a/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java b/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java index 701d0d8..94984e0 100644 --- a/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java +++ b/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java @@ -98,6 +98,7 @@ public T take() throws InterruptedException { } } +@SuppressWarnings("InfiniteLoopStatement") public class BlockingQueueApp { public static void main(String[] args) throws InterruptedException { @@ -109,9 +110,7 @@ public void run() { while (true) { blockingQueue.put(random.nextInt(10)); } - } catch (InterruptedException e) { - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} } }); @@ -126,9 +125,7 @@ public void run() { while (true) { blockingQueue.take(); } - } catch (InterruptedException e) { - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} } }); t1.start(); diff --git a/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java b/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java index 2c4f7e7..18e965d 100644 --- a/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java +++ b/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java @@ -3,32 +3,42 @@ import java.util.Scanner; /** - * Some background knowledge - * Source:http://www.programcreek.com/2009/02/notify-and-wait-example/ - * synchronized keyword is used for exclusive accessing. To make a method - * synchronized, simply add the synchronized keyword to its declaration. Then no - * two invocations of synchronized methods on the same object can interleave - * with each other. Synchronized statements must specify the object that - * provides the intrinsic lock. When synchronized(this) is used, you have to - * avoid to synchronizing invocations of other objects' methods. wait() tells + * Some background knowledge
+ * Source: http://www.programcreek.com/2009/02/notify-and-wait-example/ + *

+ * {@code synchronized} keyword is used for exclusive accessing. To make a + * method {@code synchronized}, simply add the {@code synchronized} keyword to its + * declaration. + * Then no two invocations of synchronized methods on the same object can + * interleave with each other. + *
+ * Synchronized statements must specify the object that + * provides the intrinsic lock. When {@code synchronized(this)} is used, you + * have to avoid to synchronizing invocations of other objects' methods. + *
+ * {@link Object#wait()} tells * the calling thread to give up the lock and go to sleep (not polling) until - * some other thread enters the same lock and calls notify(). notify() wakes up - * the first thread that called wait() on the same object. - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + * some other thread enters the same lock and calls {@link Object#notify()}. + *
+ * {@link Object#notify()} wakes up the first thread that called wait() on + * the same object. + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ public class Processor { - /** + /* * public synchronized void getSomething(){ this.hello = "hello World"; } * public void getSomething(){ synchronized(this){ this.hello = "hello * World"; } } * two code blocks by specification, functionally identical. */ + + public void produce() throws InterruptedException { synchronized (this) { System.out.println("Producer thread running ...."); From b15dc757afedb3709c7e5e0b6af3499acff48a3f Mon Sep 17 00:00:00 2001 From: IOAyman Date: Sun, 11 Jan 2015 18:42:53 +0100 Subject: [PATCH 06/21] JavaDoc optimized for packages 10 --- .../src/ReentrantLocks_10/App.java | 82 ++++++++++++------- .../src/ReentrantLocks_10/Runner.java | 53 +++++++----- .../src/WaitAndNotify_8/BlockingQueueApp.java | 7 +- 3 files changed, 89 insertions(+), 53 deletions(-) diff --git a/JavaMultiThreadingCodes/src/ReentrantLocks_10/App.java b/JavaMultiThreadingCodes/src/ReentrantLocks_10/App.java index 96a43b8..3e17bff 100644 --- a/JavaMultiThreadingCodes/src/ReentrantLocks_10/App.java +++ b/JavaMultiThreadingCodes/src/ReentrantLocks_10/App.java @@ -1,36 +1,62 @@ package ReentrantLocks_10; /** - * the ReentrantLock class in Java as an alternative to synchronized code - * blocks. ReentrantLocks let you do all the stuff that you can do with - * synchronized, wait and notify, plus some more stuff besides that may come in + * the {@link java.util.concurrent.locks.ReentrantLock} class in Java as an + * alternative to synchronized code blocks. + *
+ * {@link java.util.concurrent.locks.ReentrantLock}s let you do all the + * stuff that you can do with {@code synchronized}, {@link Object#wait()} and + * {@link Object#notify()}, plus some more stuff. Besides that may come in * handy from time to time. - * - * Source: + *

+ * Source: * http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html - * - * ReentrantLock Extended capabilities include: - * - * The ability to have more than one condition variable per monitor. Monitors - * that use the synchronized keyword can only have one. This means reentrant - * locks support more than one wait()/notify() queue. The ability to make the - * lock "fair". "[fair] locks favor granting access to the longest-waiting + * + *

+ * {@link java.util.concurrent.locks.ReentrantLock} Extended capabilities + * include: + *
+ *
    + *
  • + * The ability to have more than one {@link java.util.concurrent.locks.Condition} + * variable per monitor. + *
  • + *
  • Monitors that use the synchronized keyword can only have one. This means + * {@link java.util.concurrent.locks.ReentrantLock}s support more than one + * {@link Object#wait()}/{@link Object#notify()} queue. + *
  • + *
  • + * The ability to make the lock "fair". + * + * "[fair] locks favor granting access to the longest-waiting * thread. Otherwise this lock does not guarantee any particular access order." - * Synchronized blocks are unfair. The ability to check if the lock is being - * held. The ability to get the list of threads waiting on the lock. - * - * The disadvantages of reentrant locks are: - * - * Need to add import statement. Need to wrap lock acquisitions in a try/finally - * block. This makes it more ugly than the synchronized keyword. The - * synchronized keyword can be put in method definitions which avoids the need - * for a block which reduces nesting. For more complete comparison of - * reentrantLocks and synchronized see + * + *
  • + *
  • Synchronized blocks are unfair.
  • + *
  • The ability to check if the lock is being + * held.
  • + *
  • The ability to get the list of threads waiting on the lock.
  • + *
+ *

+ * The disadvantages of {@link java.util.concurrent.locks.ReentrantLock}s are: + *
+ *
    + *
  • Need to add import statement.
  • + *
  • Need to wrap lock acquisitions in a try/finally block. This makes it more + * ugly than the synchronized keyword.
  • + *
  • The synchronized keyword can be put in method definitions which avoids + * the need for a block which reduces nesting.
  • + *
+ *

+ * For more complete comparison of + * {@link java.util.concurrent.locks.ReentrantLock}s and {@code synchronized} + * see: * http://guruzon.com/1/concurrency/explicit-lock-locking/difference-between-synchronized-and-reentrantlock-in-java - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + * + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ @@ -42,8 +68,7 @@ public static void main(String[] args) throws Exception { public void run() { try { runner.firstThread(); - } catch (InterruptedException e) { - e.printStackTrace(); + } catch (InterruptedException ignored) { } } }); @@ -52,8 +77,7 @@ public void run() { public void run() { try { runner.secondThread(); - } catch (InterruptedException e) { - e.printStackTrace(); + } catch (InterruptedException ignored) { } } }); diff --git a/JavaMultiThreadingCodes/src/ReentrantLocks_10/Runner.java b/JavaMultiThreadingCodes/src/ReentrantLocks_10/Runner.java index 018f5d6..4159ea3 100644 --- a/JavaMultiThreadingCodes/src/ReentrantLocks_10/Runner.java +++ b/JavaMultiThreadingCodes/src/ReentrantLocks_10/Runner.java @@ -1,36 +1,46 @@ package ReentrantLocks_10; +import java.util.Scanner; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; /** - * Source:http://www.journaldev.com/2377/java-lock-example-and-concurrency-lock-vs-synchronized - * - * Lock: This is the base interface for Lock API. It provides all the features + * Source: + * http://www.journaldev.com/2377/java-lock-example-and-concurrency-lock-vs-synchronized + *

+ * {@link java.util.concurrent.locks.Lock}: + * This is the base interface for Lock API. It provides all the features * of synchronized keyword with additional ways to create different Conditions * for locking, providing timeout for thread to wait for lock. Some of the - * important methods are lock() to acquire the lock, unlock() to release the - * lock, tryLock() to wait for lock for a certain period of time, newCondition() + * important methods are {@link java.util.concurrent.locks.Lock#lock()} to + * acquire the lock, {@link java.util.concurrent.locks.Lock#unlock()} to release + * the lock, {@link java.util.concurrent.locks.Lock#tryLock()} to wait for lock + * for a certain period of time, + * {@link java.util.concurrent.locks.Lock#newCondition()} * to create the Condition etc. - * - * ReentrantLock: This is the most widely used implementation class of Lock + *

+ * {@link java.util.concurrent.locks.ReentrantLock}: + * This is the most widely used implementation class of Lock * interface. This class implements the Lock interface in similar way as * synchronized keyword. (see App.java for more) - * - * Condition: Condition objects are similar to Object wait-notify model with + *

+ * {@link java.util.concurrent.locks.Condition}: + * Condition objects are similar to Object wait-notify model with * additional feature to create different sets of wait. A Condition object is - * always created by Lock object. Some of the important methods are await() that - * is similar to wait() and signal(), signalAll() that is similar to notify() - * and notifyAll() methods. - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + * always created by Lock object. Some of the important methods are + * {@link java.util.concurrent.locks.Condition#await()} + * that is similar to {@link Object#wait()}. + * {@link java.util.concurrent.locks.Condition#signal()} and + * {@link java.util.concurrent.locks.Condition#signalAll()} + * that are similar to + * {@link Object#notify()} and {@link Object#notifyAll()} methods. + *

+ * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * https://www.udemy.com/java-multithreading/?couponCode=FREE * * @author Z.B. Celik */ -import java.util.Scanner; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - public class Runner { private int count = 0; @@ -65,7 +75,8 @@ public void secondThread() throws InterruptedException { try { increment(); } finally { - lock.unlock();//should be written to unlock Thread whenever signal() is called + //should be written to unlock Thread whenever signal() is called + lock.unlock(); } } diff --git a/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java b/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java index 94984e0..843f7cc 100644 --- a/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java +++ b/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java @@ -50,7 +50,8 @@ * @author Z.B. Celik * */ -//For the other version of the implementation please check LowLevelProducerConsumer_9.App +//For the other version of the implementation please check +// LowLevelProducerConsumer_9.App class BlockingQueue { private Queue queue = new LinkedList<>(); @@ -69,12 +70,12 @@ public void put(T element) throws InterruptedException { try { while (queue.size() == capacity) { System.out.println("queue is full cannot put"); - notFull.await();//releases lock + notFull.await(); //releases lock } queue.add(element); System.out.println("Added to the queue " + element); - notEmpty.signal();//call waiting thread on same object + notEmpty.signal(); //calls waiting thread on the same object } finally { lock.unlock(); } From ddc9c620e831d58588b35f3b980234fe6f51d651 Mon Sep 17 00:00:00 2001 From: IOAyman Date: Wed, 14 Jan 2015 20:34:27 +0100 Subject: [PATCH 07/21] JavaDoc optimized --- .../src/Deadlock_11/Account.java | 10 +++++-- .../src/Deadlock_11/App.java | 28 +++++++++--------- .../src/Deadlock_11/Runner.java | 28 +++++++++++------- .../Worker.java | 10 +++++-- .../src/LockObjects_4/App.java | 10 +++++-- .../src/LockObjects_4/Worker.java | 12 ++++++-- .../WorkerMethodsSynchronized.java | 12 ++++++-- .../src/LowLevelProducerConsumer_9/App.java | 10 +++++-- .../LowLevelProducerConsumer_9/Processor.java | 14 ++++++--- .../src/ProducerConsumer_7/App.java | 10 +++++-- .../src/ReentrantLocks_10/App.java | 10 +++++-- .../src/ReentrantLocks_10/Runner.java | 10 +++++-- .../ApplicationAnonymous.java | 10 +++++-- .../StartingThreads_1/ApplicationExtends.java | 11 +++++-- .../ApplicationRunnable.java | 11 +++++-- .../src/ThreadPools_5/App.java | 10 +++++-- .../src/ThreadPools_5/WorkerThreadPool.java | 10 +++++-- .../src/VolatileKeyword_2/App.java | 10 +++++-- .../src/WaitAndNotify_8/App.java | 12 ++++++-- .../src/WaitAndNotify_8/BlockingQueueApp.java | 6 ++-- .../src/WaitAndNotify_8/Processor.java | 10 +++++-- README.md | 29 ++++++++++--------- 22 files changed, 200 insertions(+), 83 deletions(-) diff --git a/JavaMultiThreadingCodes/src/Deadlock_11/Account.java b/JavaMultiThreadingCodes/src/Deadlock_11/Account.java index ff7c4a7..53a1bff 100644 --- a/JavaMultiThreadingCodes/src/Deadlock_11/Account.java +++ b/JavaMultiThreadingCodes/src/Deadlock_11/Account.java @@ -1,9 +1,15 @@ package Deadlock_11; /** - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/Deadlock_11/App.java b/JavaMultiThreadingCodes/src/Deadlock_11/App.java index 3f5c797..34b51a6 100644 --- a/JavaMultiThreadingCodes/src/Deadlock_11/App.java +++ b/JavaMultiThreadingCodes/src/Deadlock_11/App.java @@ -1,16 +1,23 @@ package Deadlock_11; /** - * Deadlock can occur in a situation when a thread is waiting for an object - * lock, that is acquired by another thread and second thread is waiting for an + * Deadlock + * can occur in a situation when a thread is waiting for an object's lock, + * that is acquired by another thread and the second thread is waiting for an * object lock that is acquired by first thread. Since, both threads are waiting * for each other to release the lock, the condition is called deadlock. If you * make sure that all locks are always taken in the same order by any thread, * deadlocks cannot occur. - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + *

+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ @@ -22,10 +29,7 @@ public static void main(String[] args) throws Exception { public void run() { try { runner.firstThread(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} } }); @@ -33,10 +37,7 @@ public void run() { public void run() { try { runner.secondThread(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} } }); @@ -46,5 +47,4 @@ public void run() { t2.join(); runner.finished(); } - } diff --git a/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java b/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java index 970d502..dd03680 100644 --- a/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java +++ b/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java @@ -1,19 +1,25 @@ - package Deadlock_11; +package Deadlock_11; -/** - * Deadlocks - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ - * also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE - * - * @author Z.B. Celik - */ import java.util.Random; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -public class Runner { + /** + * Deadlock + *

+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * + * @author Z.B. Celik + */ + public class Runner { private Account acc1 = new Account(); private Account acc2 = new Account(); diff --git a/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java b/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java index a419f3c..e89df8a 100644 --- a/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java +++ b/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java @@ -7,9 +7,15 @@ * {@code synchronized} ("only let one thread in here at a time".) and {@code join} ("wait until * thread on which join has called finished") keyword. *

- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/LockObjects_4/App.java b/JavaMultiThreadingCodes/src/LockObjects_4/App.java index e98d96f..c7941fb 100644 --- a/JavaMultiThreadingCodes/src/LockObjects_4/App.java +++ b/JavaMultiThreadingCodes/src/LockObjects_4/App.java @@ -1,9 +1,15 @@ package LockObjects_4; /** - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/LockObjects_4/Worker.java b/JavaMultiThreadingCodes/src/LockObjects_4/Worker.java index fd5d7a7..70ad012 100644 --- a/JavaMultiThreadingCodes/src/LockObjects_4/Worker.java +++ b/JavaMultiThreadingCodes/src/LockObjects_4/Worker.java @@ -10,10 +10,16 @@ * making the method synchronized or making an object inside the method * synchronized, By defining two different locks we say that one thread may * execute the stageOne while other executes stageTwo. - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + *

+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/LockObjects_4/WorkerMethodsSynchronized.java b/JavaMultiThreadingCodes/src/LockObjects_4/WorkerMethodsSynchronized.java index d122f57..c01b492 100644 --- a/JavaMultiThreadingCodes/src/LockObjects_4/WorkerMethodsSynchronized.java +++ b/JavaMultiThreadingCodes/src/LockObjects_4/WorkerMethodsSynchronized.java @@ -10,10 +10,16 @@ * making the method synchronized or making "different" objects inside the * method synchronized, By defining two different locks we say that one thread * may execute the stageOne while other executes stageTwo. - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + *

+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/App.java b/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/App.java index 3e62cf3..aabbfd3 100644 --- a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/App.java +++ b/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/App.java @@ -8,9 +8,15 @@ * the best way); but this tutorial will help you to understand how to use wait * and notify. *

- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java b/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java index e9f5a1d..e061c1d 100644 --- a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java +++ b/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java @@ -1,15 +1,21 @@ package LowLevelProducerConsumer_9; +import java.util.LinkedList; +import java.util.Random; + /** - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at + * * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ -import java.util.LinkedList; -import java.util.Random; - @SuppressWarnings("InfiniteLoopStatement") public class Processor { diff --git a/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java b/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java index 1f62f46..b064da4 100644 --- a/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java +++ b/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java @@ -8,9 +8,15 @@ * data items and adding them to a shared data store of some kind while one or * more other threads process those items, removing them from the data store. *

- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/ReentrantLocks_10/App.java b/JavaMultiThreadingCodes/src/ReentrantLocks_10/App.java index 3e17bff..845fbe7 100644 --- a/JavaMultiThreadingCodes/src/ReentrantLocks_10/App.java +++ b/JavaMultiThreadingCodes/src/ReentrantLocks_10/App.java @@ -54,9 +54,15 @@ * http://guruzon.com/1/concurrency/explicit-lock-locking/difference-between-synchronized-and-reentrantlock-in-java * *

- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/ReentrantLocks_10/Runner.java b/JavaMultiThreadingCodes/src/ReentrantLocks_10/Runner.java index 4159ea3..b97b4af 100644 --- a/JavaMultiThreadingCodes/src/ReentrantLocks_10/Runner.java +++ b/JavaMultiThreadingCodes/src/ReentrantLocks_10/Runner.java @@ -35,9 +35,15 @@ * that are similar to * {@link Object#notify()} and {@link Object#notifyAll()} methods. *

- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java index fd61eb2..8e11f90 100644 --- a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java +++ b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java @@ -3,9 +3,15 @@ /** * Starting threads using the Thread constructor with anonymous classes *

- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationExtends.java b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationExtends.java index e966135..68d346a 100644 --- a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationExtends.java +++ b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationExtends.java @@ -3,8 +3,15 @@ /** * Starting Threads with extends *

- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
- * also freely available at https://www.udemy.com/java-multithreading/?couponCode=FREE + * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationRunnable.java b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationRunnable.java index 768cfc3..a7561e3 100644 --- a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationRunnable.java +++ b/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationRunnable.java @@ -3,8 +3,15 @@ /** * Starting Threads using Runnable Interface *

- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
- * also freely available at: https://www.udemy.com/java-multithreading/?couponCode=FREE + * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/ThreadPools_5/App.java b/JavaMultiThreadingCodes/src/ThreadPools_5/App.java index 649ea6c..3cc0c33 100644 --- a/JavaMultiThreadingCodes/src/ThreadPools_5/App.java +++ b/JavaMultiThreadingCodes/src/ThreadPools_5/App.java @@ -3,9 +3,15 @@ /** * ThreadPool ("number of workers in a factory") *

- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java b/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java index 5da9ee5..6251a4f 100644 --- a/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java +++ b/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java @@ -10,9 +10,15 @@ /** * This is the implementation of {@link LockObjects_4.Worker} with threadPool *

- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/VolatileKeyword_2/App.java b/JavaMultiThreadingCodes/src/VolatileKeyword_2/App.java index c133425..027ac29 100644 --- a/JavaMultiThreadingCodes/src/VolatileKeyword_2/App.java +++ b/JavaMultiThreadingCodes/src/VolatileKeyword_2/App.java @@ -4,9 +4,15 @@ * Volatile Keyword, “… the volatile modifier guarantees that any thread that * reads a field will see the most recently written value.” - Josh Bloch *

- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/WaitAndNotify_8/App.java b/JavaMultiThreadingCodes/src/WaitAndNotify_8/App.java index f45c252..c6e2b07 100644 --- a/JavaMultiThreadingCodes/src/WaitAndNotify_8/App.java +++ b/JavaMultiThreadingCodes/src/WaitAndNotify_8/App.java @@ -6,10 +6,16 @@ * that allow you to have one or more threads sleeping, only to be woken up by * other threads at the right moment. Extremely useful for avoiding those * processor-consuming "polling loops". - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ *

+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java b/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java index 843f7cc..99f76ca 100644 --- a/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java +++ b/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java @@ -47,8 +47,8 @@ * safely take out the first connection. This checking and removing will be * atomic because we have the lock on the list. * - * @author Z.B. Celik * + * @author Z.B. Celik */ //For the other version of the implementation please check // LowLevelProducerConsumer_9.App @@ -86,12 +86,12 @@ public T take() throws InterruptedException { try { while (queue.isEmpty()) { System.out.println("queue is empty, cannot take"); - notEmpty.await();//releases lock + notEmpty.await(); //releases lock } T item = queue.remove(); System.out.println("Removed to the queue " + item); - notFull.signal();//call waiting thread on same object + notFull.signal(); //calls waiting thread on same object return item; } finally { lock.unlock(); diff --git a/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java b/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java index 18e965d..21171c1 100644 --- a/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java +++ b/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java @@ -23,9 +23,15 @@ * {@link Object#notify()} wakes up the first thread that called wait() on * the same object. *

- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ diff --git a/README.md b/README.md index 873dc08..d848712 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,8 @@ for more information. Contributor ---------- -[Z.B. Celik] (http://www.linkedin.com/in/berkaycelik) +[Z.B. Celik] (http://www.linkedin.com/in/berkaycelik) +[@IOAyman] (https://twitter.com/IOAyman) Java Multithreading Topics: @@ -17,16 +18,16 @@ Codes with minor comments are from http://www.caveofprogramming.com/youtube/ al - 1- Java Multithreading: Starting Threads -- 2- Java Multithreading: Volatile – Basic Thread Communication -- 3- Java Multithreading: Synchronized -- 4- Java Multithreading: Lock Objects -- 5- Java Multithreading: Thread Pools -- 6- Java Multithreading: Countdown Latches -- 7- Java Multithreading: Producer-Consumer -- 8- Java Multithreading: Wait and Notify -- 9- Java Multithreading: Low-Level Producer-Consumer -- 10- Java Multithreading: Re-entrant Locks -- 11- Java Multithreading: Deadlock -- 12- Java Multithreading: Semaphores -- 13- Java Multithreading: Callable and Future -- 14- Java Multithreading: Interrupting Threads +- 2- Java Multithreading: Volatile – Basic Thread Communication +- 3- Java Multithreading: Synchronized +- 4- Java Multithreading: Lock Objects +- 5- Java Multithreading: Thread Pools +- 6- Java Multithreading: Countdown Latches +- 7- Java Multithreading: Producer-Consumer +- 8- Java Multithreading: Wait and Notify +- 9- Java Multithreading: Low-Level Producer-Consumer +- 10- Java Multithreading: Re-entrant Locks +- 11- Java Multithreading: Deadlock +- 12- Java Multithreading: Semaphores +- 13- Java Multithreading: Callable and Future +- 14- Java Multithreading: Interrupting Threads From 9192686c96f0bd98a4152c6755d3d32585620dd9 Mon Sep 17 00:00:00 2001 From: IOAyman Date: Fri, 23 Jan 2015 22:04:08 +0100 Subject: [PATCH 08/21] JavaDoc optimized --- .../src/Deadlock_11/Runner.java | 45 +++++------- .../src/Deadlock_11/SimpleDeadLock.java | 10 +-- .../src/Semaphores_12/App.java | 47 +++++++----- .../src/Semaphores_12/Connection.java | 51 +++++++++---- .../src/Semaphores_12/Connectionn.java | 73 +++++++++++++++++++ 5 files changed, 163 insertions(+), 63 deletions(-) create mode 100644 JavaMultiThreadingCodes/src/Semaphores_12/Connectionn.java diff --git a/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java b/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java index dd03680..970a867 100644 --- a/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java +++ b/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java @@ -4,22 +4,23 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; - /** - * Deadlock - *

- * Codes with minor comments are from - * - * http://www.caveofprogramming.com/youtube/ - * - *
- * also freely available at - * - * https://www.udemy.com/java-multithreading/?couponCode=FREE - * - * - * @author Z.B. Celik - */ - public class Runner { +/** + * Deadlock + *

+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * + * @author Z.B. Celik + */ +@SuppressWarnings("InfiniteLoopStatement") +public class Runner { private Account acc1 = new Account(); private Account acc2 = new Account(); @@ -44,15 +45,9 @@ private void acquireLocks(Lock firstLock, Lock secondLock) throws InterruptedExc gotFirstLock = firstLock.tryLock(); gotSecondLock = secondLock.tryLock(); } finally { - if (gotFirstLock && gotSecondLock) { - return; - } - if (gotFirstLock) { - firstLock.unlock(); - } - if (gotSecondLock) { - secondLock.unlock(); - } + if (gotFirstLock && gotSecondLock) return; + else if (gotFirstLock) firstLock.unlock(); + else if (gotSecondLock) secondLock.unlock(); } // Locks not acquired Thread.sleep(1); diff --git a/JavaMultiThreadingCodes/src/Deadlock_11/SimpleDeadLock.java b/JavaMultiThreadingCodes/src/Deadlock_11/SimpleDeadLock.java index 10a9594..9ad7f65 100644 --- a/JavaMultiThreadingCodes/src/Deadlock_11/SimpleDeadLock.java +++ b/JavaMultiThreadingCodes/src/Deadlock_11/SimpleDeadLock.java @@ -2,7 +2,9 @@ /** * Source: http://www.herongyang.com/Java/Deadlock-What-Is-Deadlock.html - * Deadlock is a programming situation where two or more threads are blocked + *

+ * Deadlock + * is a programming situation where two or more threads are blocked * forever, this situation arises with at least two threads and two or more * resources. * @@ -28,8 +30,7 @@ public void run() { System.out.println("Thread 1: Holding lock 1..."); try { Thread.sleep(10); - } catch (InterruptedException ignored) { - } + } catch (InterruptedException ignored) {} System.out.println("Thread 1: Waiting for lock 2..."); synchronized (lock2) { System.out.println("Thread 2: Holding lock 1 & 2..."); @@ -45,8 +46,7 @@ public void run() { System.out.println("Thread 2: Holding lock 2..."); try { Thread.sleep(10); - } catch (InterruptedException ignored) { - } + } catch (InterruptedException ignored) {} System.out.println("Thread 2: Waiting for lock 1..."); synchronized (lock1) { System.out.println("Thread 2: Holding lock 2 & 1..."); diff --git a/JavaMultiThreadingCodes/src/Semaphores_12/App.java b/JavaMultiThreadingCodes/src/Semaphores_12/App.java index 6c1790b..154da74 100644 --- a/JavaMultiThreadingCodes/src/Semaphores_12/App.java +++ b/JavaMultiThreadingCodes/src/Semaphores_12/App.java @@ -5,34 +5,45 @@ import java.util.concurrent.TimeUnit; /** - * Semaphores are mainly used to limit the number of simultaneous threads that + * {@link java.util.concurrent.Semaphore}s + * are mainly used to limit the number of simultaneous threads that * can access a resources, but you can also use them to implement deadlock * recovery systems since a semaphore with one permit is basically a lock that - * you can unlock from other threads. - * + * can unlock from other threads. + *
* Source: + * * http://stackoverflow.com/questions/771347/what-is-mutex-and-semaphore-in-java-what-is-the-main-difference - * - * Mutex is basically mutual exclusion. Only one thread can acquire the resource - * at once. When one thread acquires the resource, no other thread is allowed to - * acquire the resource until the thread owning the resource releases. All - * threads waiting for acquiring resource would be blocked. - * + * + *

+ * Mutex (or a semaphore initialized to 1; meaning there's only one resource) + * is basically a mutual exclusion; Only one thread can acquire the resource + * at once, and all other threads trying to acquire the resource are blocked + * until the thread owning the resource releases. + *

* Semaphore is used to control the number of threads executing. There will be * fixed set of resources. The resource count will gets decremented every time * when a thread owns the same. When the semaphore count reaches 0 then no other * threads are allowed to acquire the resource. The threads get blocked till * other threads owning resource releases. - * + *

+ *

* In short, the main difference is how many threads are allowed to acquire the - * resource at once ? - * + * resource at once. + * TODO -- go a little more in depth explaining that * Mutex --its ONE. Semaphore -- its DEFINED_COUNT, ( as many as semaphore * count) - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + *

+ *

+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ @@ -40,13 +51,15 @@ public class App { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newCachedThreadPool(); - for (int i = 0; i < 13; i++) { //200 hundred times will be called + + for (int i = 0; i < 20; i++) { //200 hundred times will be called executor.submit(new Runnable() { public void run() { - Connection.getInstance().connect(); + Connectionn.getInstance().connect(); } }); } + executor.shutdown(); executor.awaitTermination(1, TimeUnit.DAYS); } diff --git a/JavaMultiThreadingCodes/src/Semaphores_12/Connection.java b/JavaMultiThreadingCodes/src/Semaphores_12/Connection.java index b4c77d7..88836e2 100644 --- a/JavaMultiThreadingCodes/src/Semaphores_12/Connection.java +++ b/JavaMultiThreadingCodes/src/Semaphores_12/Connection.java @@ -4,19 +4,38 @@ /** * Semaphores - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + *

+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ public class Connection { private static Connection instance = new Connection(); - //limit connections to 10 - //true means whichever the thread call the acquire first gets it first, - //in queue placed first to obtain the permit. +/* + limit connections to 10 + true means whichever thread gets first in the waiting pool (queue) + waiting to acquire a resource, is first to obtain the permit. + + Note that I called it a pool! + The reason is when you say "Queue", you're saying that things are + scheduled to be FIFO (First In First Out) .. which is not always the case + here! + When you initialize the semaphore with Fairness, by setting its second + argument to true, it will treat the waiting threads like FIFO. + But, + it doesn't have to be that way if you don't set on the fairness. the JVM + may schedule the waiting threads in some other manner that it sees best + (See the Java specifications for that). +*/ private Semaphore sem = new Semaphore(10, true); private int connections = 0; @@ -29,16 +48,18 @@ public static Connection getInstance() { public void connect() { try { - sem.acquire(); // get permit decrease the sem value, if 0 wait for release - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - try { + + // get permit decrease the sem value, if 0 wait for release + sem.acquire(); + //if doConnect throws and exception is still releases the permit - //so we use a separate method here to increase the connections count. + //so we use a separate method here to increase the connections count doConnect(); + + } catch (InterruptedException ignored) { } finally { - sem.release();// release permit, increase the sem value and activate waiting thread + //release permit, increase the sem value and activate waiting thread + sem.release(); } } @@ -51,9 +72,7 @@ public void doConnect() { //do your job System.out.println("Working on connections " + Thread.currentThread().getName()); Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} //when exit doConnect method decrement number of connections synchronized (this) {//atomic connections--; diff --git a/JavaMultiThreadingCodes/src/Semaphores_12/Connectionn.java b/JavaMultiThreadingCodes/src/Semaphores_12/Connectionn.java new file mode 100644 index 0000000..0171cc7 --- /dev/null +++ b/JavaMultiThreadingCodes/src/Semaphores_12/Connectionn.java @@ -0,0 +1,73 @@ +package Semaphores_12; + +import java.util.concurrent.Semaphore; + +/** + * Semaphores + *

+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * + * @author Z.B. Celik + */ +public class Connectionn { + + private static Connectionn instance = new Connectionn(); + /* + limit connections to 10 + true means whichever thread gets first in the waiting pool (queue) + waiting to acquire a resource, is first to obtain the permit. + + Note that I called it a pool! + The reason is when you say "Queue", you're saying that things are + scheduled to be FIFO (First In First Out) .. which is not always the case + here! + When you initialize the semaphore with Fairness, by setting its second + argument to true, it will treat the waiting threads like FIFO. + But, + it doesn't have to be that way if you don't set on the fairness. the JVM + may schedule the waiting threads in some other manner that it sees best + (See the Java specifications for that). + */ + private Semaphore sem = new Semaphore(10, true); + + private Connectionn() { + } + + public static Connectionn getInstance() { + return instance; + } + + public void connect() { + try { + + // get permit decrease the sem value, if 0 wait for release + sem.acquire(); + + System.out.printf("%s:: Current connections (max 10 allowed): %d\n", + Thread.currentThread().getName(), + sem.availablePermits()); + + //do your job + System.out.printf("%s:: WORKING...\n", + Thread.currentThread().getName()); + Thread.sleep(2000); + + System.out.printf("%s:: Connection released. Permits Left = %d\n", + Thread.currentThread().getName(), + sem.availablePermits()); + + } catch (InterruptedException ignored) { + } finally { + //release permit, increase the sem value and activate waiting thread + sem.release(); + } + } +} From bfa2172b30396822b8e1829df70e62cec87af769 Mon Sep 17 00:00:00 2001 From: IOAyman Date: Sat, 24 Jan 2015 09:02:17 +0100 Subject: [PATCH 09/21] Replaced the IOException with a TimeoutException (better example :P ) JavaDoc optimized --- .../src/CallableAndFuture_13/App.java | 60 ++++++++++--------- 1 file changed, 32 insertions(+), 28 deletions(-) diff --git a/JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java b/JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java index 46c2a9b..2280984 100644 --- a/JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java +++ b/JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java @@ -1,67 +1,71 @@ package CallableAndFuture_13; +import java.util.Random; +import java.util.concurrent.*; + /** - * Callable and Future in Java to get results from your threads and to allow + * {@link java.util.concurrent.Callable} and + * {@link java.util.concurrent.Future} + * in Java to get results from your threads and to allow * your threads to throw exceptions. Plus, Future allows you to control your * threads, checking to see if they’re running or not, waiting for results and - * even interrupting them or descheduling them. - * - * Runnable is default abstraction for creating a task in Java. It has a single - * method run() that accepts no arguments and returns no value, nor it can throw + * even interrupting them or de-scheduling them. + *

+ * {@link java.lang.Runnable} + * is the default abstraction for creating a task in Java. It has a single + * method {@link Runnable#run()} + * that accepts no arguments and returns no value, nor it can throw * any checked exception. To overcome these limitations, Java 5 introduced a new - * task abstraction through Callable interface. - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + * task abstraction through {@link java.util.concurrent.Callable} interface. + *

+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ -import java.io.IOException; -import java.util.Random; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - public class App { public static void main(String[] args) throws InterruptedException { ExecutorService executor = Executors.newCachedThreadPool(); + //anonymous call of Callable Future future = executor.submit(new Callable() { @Override //return value is Integer - public Integer call() throws Exception { + public Integer call() throws TimeoutException { Random random = new Random(); int duration = random.nextInt(4000); if (duration > 2000) { - throw new IOException("Sleeping for too long."); + throw new TimeoutException ("Sleeping for too long."); } - System.out.println("Starting ..."); + System.out.println("Starting ..."); try { Thread.sleep(duration); - } catch (InterruptedException e) { - e.printStackTrace(); - } + } catch (InterruptedException ignored) {} System.out.println("Finished."); return duration; } }); executor.shutdown(); - executor.awaitTermination(1, TimeUnit.DAYS); +// executor.awaitTermination(1, TimeUnit.DAYS); try { //get returned value from call() System.out.println("Result is: " + future.get()); - } catch (InterruptedException e) { - e.printStackTrace(); + + } catch (InterruptedException ignored) { + } catch (ExecutionException e) { - IOException ex = (IOException) e.getCause(); + TimeoutException ex = (TimeoutException) e.getCause(); System.out.println(ex.getMessage()); } } From b83db5e3d199ead351efa679271ec275a0d9ffa6 Mon Sep 17 00:00:00 2001 From: IOAyman Date: Sat, 24 Jan 2015 09:19:24 +0100 Subject: [PATCH 10/21] JavaDoc optimized Added myself to README.md --- .../src/CallableAndFuture_13/App2.java | 21 +++--- .../CallableAndFuture_13/CallableTester.java | 69 +++++++++++-------- README.md | 11 ++- 3 files changed, 53 insertions(+), 48 deletions(-) diff --git a/JavaMultiThreadingCodes/src/CallableAndFuture_13/App2.java b/JavaMultiThreadingCodes/src/CallableAndFuture_13/App2.java index 426b95b..3fb721b 100644 --- a/JavaMultiThreadingCodes/src/CallableAndFuture_13/App2.java +++ b/JavaMultiThreadingCodes/src/CallableAndFuture_13/App2.java @@ -1,23 +1,18 @@ package CallableAndFuture_13; +import java.util.ArrayList; +import java.util.concurrent.*; + /** * Understanding Callable * * @author Z.B. Celik */ -import java.util.ArrayList; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - class MyCallable implements Callable { - Integer value; + int value; - public MyCallable(Integer i) { + public MyCallable(int i) { this.value = i; } @@ -38,8 +33,8 @@ public class App2 { public static void main(String[] args) throws InterruptedException { ArrayList list = new ArrayList<>(); ExecutorService executor = Executors.newCachedThreadPool(); - Future future = null; - Callable callable = null; + Future future; + for (int i = 1; i < 10; i++) { future = executor.submit(new MyCallable(i)); try { @@ -50,7 +45,9 @@ public static void main(String[] args) throws InterruptedException { } executor.shutdown(); + //this is ont necessary in this case .. but .. good practice :) executor.awaitTermination(1, TimeUnit.DAYS); + for (int i = 0; i < list.size(); i++) { //get returned values from call() System.out.println("List Values " + i + " Value: " + list.get(i)); diff --git a/JavaMultiThreadingCodes/src/CallableAndFuture_13/CallableTester.java b/JavaMultiThreadingCodes/src/CallableAndFuture_13/CallableTester.java index 8fd3511..eb9779c 100644 --- a/JavaMultiThreadingCodes/src/CallableAndFuture_13/CallableTester.java +++ b/JavaMultiThreadingCodes/src/CallableAndFuture_13/CallableTester.java @@ -1,33 +1,47 @@ package CallableAndFuture_13; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.*; /** - * Source:http://java-x.blogspot.com.tr/2006/11/java-5-concurrency-callable-and-future.html - * Till Java 1.4, threads could be implemented by either implementing Runnable - * or extending Thread. This was quite simple, but had a serious limitation - + * Source: + * + * http://java-x.blogspot.com.tr/2006/11/java-5-concurrency-callable-and-future.html + * + *

+ * Till Java 1.4, threads could be implemented by either implementing + * {@link java.lang.Runnable} or extending {@link java.lang.Thread}. + * This was quite simple, but had a serious limitation; * They have a run method that cannot return values. In order to side-step this, * most programmers use side-effects (writing to a file etc.) to mimic returning - * values to the invoker of the thread. Java 5 introduces the Callable - * interface, that allows users to return values from a thread - * - * Runnable vs Callable - * Runnable Introduced in Java 1.0 Callable Introduced in Java 1.5 as part of - * java.util.concurrent library - * - * Runnable cannot be parametrized Callable is a parametrized type whose type - * parameter indicates the return type of its run method Classes implementing - * + * values to the invoker of the thread. Java 5 introduces the + * {@link java.util.concurrent.Callable} interface, that allows users to + * return values from a thread. + *

+ *

+ * {@link java.lang.Runnable} vs {@link java.util.concurrent.Callable} : + *

    + *
  • + * Runnable Introduced in Java 1.0. Callable Introduced in Java 1.5 as + * part of + * {@link java.util.concurrent} library. + *
  • + *
  • + * Runnable cannot be parametrized .Callable is a parametrized type whose type + * parameter indicates the return type of its run method Classes implementing. + *
  • + *
  • * Runnable needs to implement run() method, classes implementing Callable needs - * to implement call() method - * - * Runnable.run() returns no value, Callable.call() returns a value of Type T - * + * to implement call() method. + *
  • + *
  • + * Runnable.run() returns no value, Callable.call() returns a value of Type T. + *
  • + *
  • * Runnable can not throw checked exceptions, Callable can throw checked - * exceptions + * exceptions. + *
  • + *
+ *

* * @author Z.B. Celik */ @@ -58,7 +72,7 @@ public void setMyName(int myName) { public class CallableTester { - public static void main(String[] args) { + public static void main(String[] args) throws InterruptedException { Callable callable = new CallableImpl(2); ExecutorService executor = new ScheduledThreadPoolExecutor(1); @@ -66,12 +80,9 @@ public static void main(String[] args) { try { System.out.println("Future value: " + future.get()); - } catch (Exception e) { - e.printStackTrace(); - } finally { - executor.shutdown(); - executor.isTerminated(); - } + } catch (Exception ignored) {} + executor.shutdown(); + executor.awaitTermination(1, TimeUnit.HOURS); } } diff --git a/README.md b/README.md index d848712..09aaeb1 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,16 @@ -Java Multithreading -============================================================= +#Java Multithreading This repository will contain all the codes for the ultimate Java multithreading course by John Purcell See the [Video Tutorials](https://www.udemy.com/java-multithreading/) for more information. -Contributor ----------- -[Z.B. Celik] (http://www.linkedin.com/in/berkaycelik) +##Contributors +[Z.B. Celik] (http://www.linkedin.com/in/berkaycelik) [@IOAyman] (https://twitter.com/IOAyman) -Java Multithreading Topics: -------------- +##Java Multithreading Topics: Codes with minor comments are from http://www.caveofprogramming.com/youtube/ also freely available at https://www.udemy.com/java-multithreading/?couponCode=FREE From ee43690b2aafc8e87c705ac58a69e78d3c0d22dd Mon Sep 17 00:00:00 2001 From: IOAyman Date: Sat, 24 Jan 2015 10:37:39 +0100 Subject: [PATCH 11/21] JavaDoc optimized --- .../src/CallableAndFuture_13/App.java | 1 - .../src/InterruptingThreads14/App.java | 48 ++++++++++++------- 2 files changed, 31 insertions(+), 18 deletions(-) diff --git a/JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java b/JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java index 2280984..33624a8 100644 --- a/JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java +++ b/JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java @@ -63,7 +63,6 @@ public Integer call() throws TimeoutException { System.out.println("Result is: " + future.get()); } catch (InterruptedException ignored) { - } catch (ExecutionException e) { TimeoutException ex = (TimeoutException) e.getCause(); System.out.println(ex.getMessage()); diff --git a/JavaMultiThreadingCodes/src/InterruptingThreads14/App.java b/JavaMultiThreadingCodes/src/InterruptingThreads14/App.java index 165a460..a843f1e 100644 --- a/JavaMultiThreadingCodes/src/InterruptingThreads14/App.java +++ b/JavaMultiThreadingCodes/src/InterruptingThreads14/App.java @@ -1,27 +1,31 @@ package InterruptingThreads14; -import java.util.Random; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; /** - * how to interrupt running threads in Java using the built-in thread - * interruption mechanism. - * - * Source:http://www.javamex.com/tutorials/threads/thread_interruption.shtml - * Incidentally, it is important not to confuse thread interruption with either + * How to interrupt running threads in Java using the built-in thread + * interruption mechanism. + *

+ * Source: + * + * http://www.javamex.com/tutorials/threads/thread_interruption.shtml + *

+ * Incidentally, it is important NOT to confuse thread interruption with either * software interrupts (where the CPU automatically interrupts the current * instruction flow in order to call a registered piece of code periodically— as * in fact happens to drive the thread scheduler) and hardware interrupts (where * the CPU automatically performs a similar task in response to some hardware * signal). - * - * Codes with minor comments are from http://www.caveofprogramming.com/youtube/ + *

+ * Codes with minor comments are from + * + * http://www.caveofprogramming.com/youtube/ + * + *
* also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * * * @author Z.B. Celik */ @@ -37,20 +41,30 @@ public static void main(String[] args) throws InterruptedException { @Override public Void call() throws Exception { - Random ran = new Random(); + for (int i = 0; i < 1E8; i++) { if (Thread.currentThread().isInterrupted()) { - System.out.println("Interrupted!"); + System.out.printf("Interrupted at %d !!!", i); break; } - Math.sin(ran.nextDouble()); } + return null; } }); executor.shutdown(); Thread.sleep(500); + + /* + in this example, there are different ways you can interrupt a thread + execution. + */ + + //JavaDoc: http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#cancel-boolean- +// fu.cancel(true); + + //JavaDoc: http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdownNow-- executor.shutdownNow(); executor.awaitTermination(1, TimeUnit.DAYS); From e7fa22a4bada0a276dfe7ad6e06016bc31339ec8 Mon Sep 17 00:00:00 2001 From: Santiago Castro Date: Mon, 17 Apr 2017 03:42:38 -0300 Subject: [PATCH 12/21] Fix broken Markdown headings --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 09aaeb1..4d8d968 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,16 @@ -#Java Multithreading +# Java Multithreading This repository will contain all the codes for the ultimate Java multithreading course by John Purcell See the [Video Tutorials](https://www.udemy.com/java-multithreading/) for more information. -##Contributors +## Contributors [Z.B. Celik] (http://www.linkedin.com/in/berkaycelik) [@IOAyman] (https://twitter.com/IOAyman) -##Java Multithreading Topics: +## Java Multithreading Topics: Codes with minor comments are from http://www.caveofprogramming.com/youtube/ also freely available at https://www.udemy.com/java-multithreading/?couponCode=FREE From 776124bd817cdbdaa61acec5eecf736a521a7fde Mon Sep 17 00:00:00 2001 From: Berkay Date: Thu, 2 Aug 2018 12:56:49 -0400 Subject: [PATCH 13/21] Update README.md --- README.md | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 4d8d968..8b742ea 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,11 @@ # Java Multithreading -This repository will contain all the codes for the ultimate Java multithreading course by John Purcell +This repository contains all the codes required for the ultimate Java multithreading course (by John Purcell) -See the [Video Tutorials](https://www.udemy.com/java-multithreading/) +See the course content from [here](https://www.udemy.com/java-multithreading/) or [here](http://www.caveofprogramming.com/youtube/) for more information. -## Contributors -[Z.B. Celik] (http://www.linkedin.com/in/berkaycelik) -[@IOAyman] (https://twitter.com/IOAyman) - - ## Java Multithreading Topics: -Codes with minor comments are from http://www.caveofprogramming.com/youtube/ also freely available at https://www.udemy.com/java-multithreading/?couponCode=FREE - - 1- Java Multithreading: Starting Threads - 2- Java Multithreading: Volatile – Basic Thread Communication @@ -28,3 +21,8 @@ Codes with minor comments are from http://www.caveofprogramming.com/youtube/ al - 12- Java Multithreading: Semaphores - 13- Java Multithreading: Callable and Future - 14- Java Multithreading: Interrupting Threads + + +## Contributors +[Z. Berkay Celik] (https://twitter.com/ZBerkayCelik) +[@IOAyman] (https://twitter.com/IOAyman) From 24eaf4c12fc33ffe7618d5d690855a17193569de Mon Sep 17 00:00:00 2001 From: Berkay Date: Thu, 2 Aug 2018 12:57:10 -0400 Subject: [PATCH 14/21] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 8b742ea..beb53ab 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,6 @@ This repository contains all the codes required for the ultimate Java multithreading course (by John Purcell) See the course content from [here](https://www.udemy.com/java-multithreading/) or [here](http://www.caveofprogramming.com/youtube/) -for more information. ## Java Multithreading Topics: From d6b94587346c2defff3580c19b9825d53b2df8ed Mon Sep 17 00:00:00 2001 From: Berkay Date: Sat, 18 Aug 2018 15:52:17 -0400 Subject: [PATCH 15/21] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index beb53ab..6f68b22 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ # Java Multithreading This repository contains all the codes required for the ultimate Java multithreading course (by John Purcell) -See the course content from [here](https://www.udemy.com/java-multithreading/) or [here](http://www.caveofprogramming.com/youtube/) +[See the course content](https://caveofprogramming.teachable.com/p/java-multithreading) ## Java Multithreading Topics: @@ -23,5 +23,5 @@ See the course content from [here](https://www.udemy.com/java-multithreading/) o ## Contributors -[Z. Berkay Celik] (https://twitter.com/ZBerkayCelik) +[Z. Berkay Celik] (https://twitter.com/ZBerkayCelik) [Twitter] (https://twitter.com/ZBerkayCelik) [@IOAyman] (https://twitter.com/IOAyman) From b60b1a7e4b0772e23bb1c5f6d44cc7f551d70f6a Mon Sep 17 00:00:00 2001 From: Berkay Date: Sat, 18 Aug 2018 15:52:42 -0400 Subject: [PATCH 16/21] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 6f68b22..a1ff932 100644 --- a/README.md +++ b/README.md @@ -24,4 +24,5 @@ This repository contains all the codes required for the ultimate Java multithrea ## Contributors [Z. Berkay Celik] (https://twitter.com/ZBerkayCelik) [Twitter] (https://twitter.com/ZBerkayCelik) + [@IOAyman] (https://twitter.com/IOAyman) From a698052ca6763c82b24b0ee5b40e9580f0997e72 Mon Sep 17 00:00:00 2001 From: Berkay Date: Sat, 18 Aug 2018 15:53:08 -0400 Subject: [PATCH 17/21] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a1ff932..133086e 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,6 @@ This repository contains all the codes required for the ultimate Java multithrea ## Contributors -[Z. Berkay Celik] (https://twitter.com/ZBerkayCelik) [Twitter] (https://twitter.com/ZBerkayCelik) +[Z. Berkay Celik](https://twitter.com/ZBerkayCelik) [Twitter](https://twitter.com/ZBerkayCelik) -[@IOAyman] (https://twitter.com/IOAyman) +[@IOAyman](https://twitter.com/IOAyman) From 789835532e398589e1bf8b597b7bd6f7fe7b4188 Mon Sep 17 00:00:00 2001 From: Berkay Date: Sat, 18 Aug 2018 15:53:33 -0400 Subject: [PATCH 18/21] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 133086e..914a2b6 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,6 @@ This repository contains all the codes required for the ultimate Java multithrea ## Contributors -[Z. Berkay Celik](https://twitter.com/ZBerkayCelik) [Twitter](https://twitter.com/ZBerkayCelik) +[Z. Berkay Celik](https://twitter.com/ZBerkayCelik) [@IOAyman](https://twitter.com/IOAyman) From 8cf3b6e79a151fc81e3326c33d6d24213007740a Mon Sep 17 00:00:00 2001 From: Berkay Date: Sat, 27 Oct 2018 21:20:51 -0400 Subject: [PATCH 19/21] Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 914a2b6..9938653 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,7 @@ # Java Multithreading -This repository contains all the codes required for the ultimate Java multithreading course (by John Purcell) +This repository contains all the codes required for the ultimate Java multithreading course. We recommend the codes for those interested in understanding the multithreading. The code is written in Java and the topics are numbered by following the lecture content of John Purcell's Java-MultiThreading (https://caveofprogramming.teachable.com/p/java-multithreading) course. -[See the course content](https://caveofprogramming.teachable.com/p/java-multithreading) ## Java Multithreading Topics: From f0025ce4ad812473f1dcae6181d25269347cf494 Mon Sep 17 00:00:00 2001 From: Berkay Date: Sat, 27 Oct 2018 21:21:34 -0400 Subject: [PATCH 20/21] Update README.md read me updated. --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 9938653..ee45668 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,5 @@ - # Java Multithreading -This repository contains all the codes required for the ultimate Java multithreading course. We recommend the codes for those interested in understanding the multithreading. The code is written in Java and the topics are numbered by following the lecture content of John Purcell's Java-MultiThreading (https://caveofprogramming.teachable.com/p/java-multithreading) course. +This repository contains all the codes required for the ultimate Java multithreading course. We recommend the codes for those interested in understanding the multithreading. The code is written in Java and the topics are numbered by following the lecture content of John Purcell's [Java-MultiThreading](https://caveofprogramming.teachable.com/p/java-multithreading) course. ## Java Multithreading Topics: From 2dac69bb8e2706d60711b1b65a12437190e18c31 Mon Sep 17 00:00:00 2001 From: Berkay Date: Sun, 28 Oct 2018 05:35:05 -0400 Subject: [PATCH 21/21] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ee45668..6d91e04 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # Java Multithreading -This repository contains all the codes required for the ultimate Java multithreading course. We recommend the codes for those interested in understanding the multithreading. The code is written in Java and the topics are numbered by following the lecture content of John Purcell's [Java-MultiThreading](https://caveofprogramming.teachable.com/p/java-multithreading) course. +This repository contains all the codes required for the ultimate John Purcell's [Java-MultiThreading](https://caveofprogramming.teachable.com/p/java-multithreading) course. + +We recommend the codes for those interested in understanding the multithreading. The code is written in Java and the topics are numbered by following the lecture content. ## Java Multithreading Topics: