From bc842ccbed23cc4ac64c806b385a60257d2f8029 Mon Sep 17 00:00:00 2001 From: jsimas Date: Mon, 29 May 2017 17:20:37 +0100 Subject: [PATCH 1/2] Refactoring project --- .gitignore | 3 + .../src => src}/CallableAndFuture_13/App.java | 144 ++++----- .../CallableAndFuture_13/App2.java | 114 ++++---- .../CallableAndFuture_13/CallableTester.java | 176 +++++------ .../src => src}/CountDownLatch_6/App.java | 156 +++++----- .../src => src}/Deadlock_11/Account.java | 72 ++--- .../src => src}/Deadlock_11/App.java | 0 .../src => src}/Deadlock_11/Runner.java | 182 ++++++------ .../Deadlock_11/SimpleDeadLock.java | 114 ++++---- .../InterruptingThreads14/App.java | 148 +++++----- .../Worker.java | 0 .../src => src}/LockObjects_4/App.java | 52 ++-- .../src => src}/LockObjects_4/Worker.java | 198 ++++++------- .../WorkerMethodsSynchronized.java | 188 ++++++------ .../LowLevelProducerConsumer_9/App.java | 110 +++---- .../LowLevelProducerConsumer_9/Processor.java | 118 ++++---- .../src => src}/ProducerConsumer_7/App.java | 180 ++++++------ .../src => src}/ReentrantLocks_10/App.java | 196 ++++++------- .../src => src}/ReentrantLocks_10/Runner.java | 184 ++++++------ .../src => src}/Semaphores_12/App.java | 132 ++++----- .../src => src}/Semaphores_12/Connection.java | 164 +++++------ .../Semaphores_12/Connectionn.java | 146 +++++----- .../ApplicationAnonymous.java | 74 ++--- .../StartingThreads_1/ApplicationExtends.java | 0 .../ApplicationRunnable.java | 86 +++--- .../src => src}/ThreadPools_5/App.java | 116 ++++---- .../ThreadPools_5/WorkerThreadPool.java | 192 ++++++------ .../src => src}/VolatileKeyword_2/App.java | 0 .../src => src}/WaitAndNotify_8/App.java | 98 +++---- .../WaitAndNotify_8/BlockingQueueApp.java | 274 +++++++++--------- .../WaitAndNotify_8/Processor.java | 136 ++++----- .../src => src}/tests.java | 0 32 files changed, 1878 insertions(+), 1875 deletions(-) create mode 100644 .gitignore rename {JavaMultiThreadingCodes/src => src}/CallableAndFuture_13/App.java (97%) rename {JavaMultiThreadingCodes/src => src}/CallableAndFuture_13/App2.java (96%) rename {JavaMultiThreadingCodes/src => src}/CallableAndFuture_13/CallableTester.java (96%) rename {JavaMultiThreadingCodes/src => src}/CountDownLatch_6/App.java (97%) rename {JavaMultiThreadingCodes/src => src}/Deadlock_11/Account.java (95%) rename {JavaMultiThreadingCodes/src => src}/Deadlock_11/App.java (100%) rename {JavaMultiThreadingCodes/src => src}/Deadlock_11/Runner.java (97%) rename {JavaMultiThreadingCodes/src => src}/Deadlock_11/SimpleDeadLock.java (96%) rename {JavaMultiThreadingCodes/src => src}/InterruptingThreads14/App.java (97%) rename {JavaMultiThreadingCodes/src => src}/JoiningAndSynchronizeThreads_3/Worker.java (100%) rename {JavaMultiThreadingCodes/src => src}/LockObjects_4/App.java (96%) rename {JavaMultiThreadingCodes/src => src}/LockObjects_4/Worker.java (96%) rename {JavaMultiThreadingCodes/src => src}/LockObjects_4/WorkerMethodsSynchronized.java (96%) rename {JavaMultiThreadingCodes/src => src}/LowLevelProducerConsumer_9/App.java (96%) rename {JavaMultiThreadingCodes/src => src}/LowLevelProducerConsumer_9/Processor.java (96%) rename {JavaMultiThreadingCodes/src => src}/ProducerConsumer_7/App.java (97%) rename {JavaMultiThreadingCodes/src => src}/ReentrantLocks_10/App.java (97%) rename {JavaMultiThreadingCodes/src => src}/ReentrantLocks_10/Runner.java (97%) rename {JavaMultiThreadingCodes/src => src}/Semaphores_12/App.java (97%) rename {JavaMultiThreadingCodes/src => src}/Semaphores_12/Connection.java (97%) rename {JavaMultiThreadingCodes/src => src}/Semaphores_12/Connectionn.java (97%) rename {JavaMultiThreadingCodes/src => src}/StartingThreads_1/ApplicationAnonymous.java (96%) rename {JavaMultiThreadingCodes/src => src}/StartingThreads_1/ApplicationExtends.java (100%) rename {JavaMultiThreadingCodes/src => src}/StartingThreads_1/ApplicationRunnable.java (96%) rename {JavaMultiThreadingCodes/src => src}/ThreadPools_5/App.java (96%) rename {JavaMultiThreadingCodes/src => src}/ThreadPools_5/WorkerThreadPool.java (97%) rename {JavaMultiThreadingCodes/src => src}/VolatileKeyword_2/App.java (100%) rename {JavaMultiThreadingCodes/src => src}/WaitAndNotify_8/App.java (96%) rename {JavaMultiThreadingCodes/src => src}/WaitAndNotify_8/BlockingQueueApp.java (97%) rename {JavaMultiThreadingCodes/src => src}/WaitAndNotify_8/Processor.java (97%) rename {JavaMultiThreadingCodes/src => src}/tests.java (100%) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3eaf567 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/bin/ +/.classpath +/.project diff --git a/JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java b/src/CallableAndFuture_13/App.java similarity index 97% rename from JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java rename to src/CallableAndFuture_13/App.java index 33624a8..1a42642 100644 --- a/JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java +++ b/src/CallableAndFuture_13/App.java @@ -1,72 +1,72 @@ -package CallableAndFuture_13; - -import java.util.Random; -import java.util.concurrent.*; - -/** - * {@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 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 {@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 - * - * - * @author Z.B. Celik - */ -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 TimeoutException { - Random random = new Random(); - int duration = random.nextInt(4000); - if (duration > 2000) { - throw new TimeoutException ("Sleeping for too long."); - } - - System.out.println("Starting ..."); - try { - Thread.sleep(duration); - } catch (InterruptedException ignored) {} - System.out.println("Finished."); - return duration; - } - }); - - executor.shutdown(); -// executor.awaitTermination(1, TimeUnit.DAYS); - try { - //get returned value from call() - System.out.println("Result is: " + future.get()); - - } catch (InterruptedException ignored) { - } catch (ExecutionException e) { - TimeoutException ex = (TimeoutException) e.getCause(); - System.out.println(ex.getMessage()); - } - } - -} +package CallableAndFuture_13; + +import java.util.Random; +import java.util.concurrent.*; + +/** + * {@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 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 {@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 + * + * + * @author Z.B. Celik + */ +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 TimeoutException { + Random random = new Random(); + int duration = random.nextInt(4000); + if (duration > 2000) { + throw new TimeoutException ("Sleeping for too long."); + } + + System.out.println("Starting ..."); + try { + Thread.sleep(duration); + } catch (InterruptedException ignored) {} + System.out.println("Finished."); + return duration; + } + }); + + executor.shutdown(); +// executor.awaitTermination(1, TimeUnit.DAYS); + try { + //get returned value from call() + 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/CallableAndFuture_13/App2.java b/src/CallableAndFuture_13/App2.java similarity index 96% rename from JavaMultiThreadingCodes/src/CallableAndFuture_13/App2.java rename to src/CallableAndFuture_13/App2.java index 3fb721b..861c520 100644 --- a/JavaMultiThreadingCodes/src/CallableAndFuture_13/App2.java +++ b/src/CallableAndFuture_13/App2.java @@ -1,57 +1,57 @@ -package CallableAndFuture_13; - -import java.util.ArrayList; -import java.util.concurrent.*; - -/** - * Understanding Callable - * - * @author Z.B. Celik - */ -class MyCallable implements Callable { - - int value; - - public MyCallable(int i) { - this.value = i; - } - - @Override - public Integer call() throws Exception { - Integer sum = 0; - for (int i = 0; i < value; i++) { - sum += i; - } - System.out.println("Sum in Callable.Call() " + sum); - return sum; - } - -} - -public class App2 { - - public static void main(String[] args) throws InterruptedException { - ArrayList list = new ArrayList<>(); - ExecutorService executor = Executors.newCachedThreadPool(); - Future future; - - for (int i = 1; i < 10; i++) { - future = executor.submit(new MyCallable(i)); - try { - list.add(future.get()); - } catch (ExecutionException ex) { - System.out.println(ex.getMessage()); - } - } - - 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)); - - } - } -} +package CallableAndFuture_13; + +import java.util.ArrayList; +import java.util.concurrent.*; + +/** + * Understanding Callable + * + * @author Z.B. Celik + */ +class MyCallable implements Callable { + + int value; + + public MyCallable(int i) { + this.value = i; + } + + @Override + public Integer call() throws Exception { + Integer sum = 0; + for (int i = 0; i < value; i++) { + sum += i; + } + System.out.println("Sum in Callable.Call() " + sum); + return sum; + } + +} + +public class App2 { + + public static void main(String[] args) throws InterruptedException { + ArrayList list = new ArrayList<>(); + ExecutorService executor = Executors.newCachedThreadPool(); + Future future; + + for (int i = 1; i < 10; i++) { + future = executor.submit(new MyCallable(i)); + try { + list.add(future.get()); + } catch (ExecutionException ex) { + System.out.println(ex.getMessage()); + } + } + + 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/src/CallableAndFuture_13/CallableTester.java similarity index 96% rename from JavaMultiThreadingCodes/src/CallableAndFuture_13/CallableTester.java rename to src/CallableAndFuture_13/CallableTester.java index eb9779c..8385aa2 100644 --- a/JavaMultiThreadingCodes/src/CallableAndFuture_13/CallableTester.java +++ b/src/CallableAndFuture_13/CallableTester.java @@ -1,88 +1,88 @@ -package CallableAndFuture_13; - -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 - * {@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 - * {@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} : - *

- *

- * - * @author Z.B. Celik - */ -class CallableImpl implements Callable { - - private int myName; - - CallableImpl(int i) { - myName = i; - } - - @Override - public Integer call() { - for (int i = 0; i < 10; i++) { - System.out.println("Thread : " + getMyName() + " value is : " + i); - } - return getMyName(); - } - - public int getMyName() { - return myName; - } - - public void setMyName(int myName) { - this.myName = myName; - } -} - -public class CallableTester { - - public static void main(String[] args) throws InterruptedException { - - Callable callable = new CallableImpl(2); - ExecutorService executor = new ScheduledThreadPoolExecutor(1); - Future future = executor.submit(callable); - - try { - System.out.println("Future value: " + future.get()); - } catch (Exception ignored) {} - executor.shutdown(); - executor.awaitTermination(1, TimeUnit.HOURS); - } - -} +package CallableAndFuture_13; + +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 + * {@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 + * {@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. + *
  • + *
  • + * Runnable can not throw checked exceptions, Callable can throw checked + * exceptions. + *
  • + *
+ *

+ * + * @author Z.B. Celik + */ +class CallableImpl implements Callable { + + private int myName; + + CallableImpl(int i) { + myName = i; + } + + @Override + public Integer call() { + for (int i = 0; i < 10; i++) { + System.out.println("Thread : " + getMyName() + " value is : " + i); + } + return getMyName(); + } + + public int getMyName() { + return myName; + } + + public void setMyName(int myName) { + this.myName = myName; + } +} + +public class CallableTester { + + public static void main(String[] args) throws InterruptedException { + + Callable callable = new CallableImpl(2); + ExecutorService executor = new ScheduledThreadPoolExecutor(1); + Future future = executor.submit(callable); + + try { + System.out.println("Future value: " + future.get()); + } catch (Exception ignored) {} + executor.shutdown(); + executor.awaitTermination(1, TimeUnit.HOURS); + } + +} diff --git a/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java b/src/CountDownLatch_6/App.java similarity index 97% rename from JavaMultiThreadingCodes/src/CountDownLatch_6/App.java rename to src/CountDownLatch_6/App.java index 20164d7..becb86e 100644 --- a/JavaMultiThreadingCodes/src/CountDownLatch_6/App.java +++ b/src/CountDownLatch_6/App.java @@ -1,78 +1,78 @@ -package CountDownLatch_6; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * {@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
- * - * Any thread, usually main thread of application, which calls - * {@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 - * {@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 {@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/
- * also freely available at - * https://www.udemy.com/java-multithreading/?couponCode=FREE - * - * @author Z.B. Celik - */ -class Processor implements Runnable { - - private CountDownLatch latch; - - public Processor(CountDownLatch latch) { - this.latch = latch; - } - - public void run() { - System.out.println("Started."); - - try { - Thread.sleep(3000); - } catch (InterruptedException ignored) {} - latch.countDown(); - } -} - -public class App { - - public static void main(String[] args) { - CountDownLatch latch = new CountDownLatch(3); - ExecutorService executor = Executors.newFixedThreadPool(3); - 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. - latch.await(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - System.out.println("Completed."); - } - -} +package CountDownLatch_6; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * {@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
+ * + * Any thread, usually main thread of application, which calls + * {@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 + * {@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 {@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/
+ * also freely available at + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * @author Z.B. Celik + */ +class Processor implements Runnable { + + private CountDownLatch latch; + + public Processor(CountDownLatch latch) { + this.latch = latch; + } + + public void run() { + System.out.println("Started."); + + try { + Thread.sleep(3000); + } catch (InterruptedException ignored) {} + latch.countDown(); + } +} + +public class App { + + public static void main(String[] args) { + CountDownLatch latch = new CountDownLatch(3); + ExecutorService executor = Executors.newFixedThreadPool(3); + 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. + latch.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + System.out.println("Completed."); + } + +} diff --git a/JavaMultiThreadingCodes/src/Deadlock_11/Account.java b/src/Deadlock_11/Account.java similarity index 95% rename from JavaMultiThreadingCodes/src/Deadlock_11/Account.java rename to src/Deadlock_11/Account.java index 53a1bff..e7a4fa2 100644 --- a/JavaMultiThreadingCodes/src/Deadlock_11/Account.java +++ b/src/Deadlock_11/Account.java @@ -1,36 +1,36 @@ -package Deadlock_11; - -/** - * 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 - */ -class Account { - - private int balance = 10000; - - public void deposit(int amount) { - balance += amount; - } - - public void withdraw(int amount) { - balance -= amount; - } - - public int getBalance() { - return balance; - } - - public static void transfer(Account acc1, Account acc2, int amount) { - acc1.withdraw(amount); - acc2.deposit(amount); - } -} +package Deadlock_11; + +/** + * 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 + */ +class Account { + + private int balance = 10000; + + public void deposit(int amount) { + balance += amount; + } + + public void withdraw(int amount) { + balance -= amount; + } + + public int getBalance() { + return balance; + } + + public static void transfer(Account acc1, Account acc2, int amount) { + acc1.withdraw(amount); + acc2.deposit(amount); + } +} diff --git a/JavaMultiThreadingCodes/src/Deadlock_11/App.java b/src/Deadlock_11/App.java similarity index 100% rename from JavaMultiThreadingCodes/src/Deadlock_11/App.java rename to src/Deadlock_11/App.java diff --git a/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java b/src/Deadlock_11/Runner.java similarity index 97% rename from JavaMultiThreadingCodes/src/Deadlock_11/Runner.java rename to src/Deadlock_11/Runner.java index 970a867..aaf6bb7 100644 --- a/JavaMultiThreadingCodes/src/Deadlock_11/Runner.java +++ b/src/Deadlock_11/Runner.java @@ -1,91 +1,91 @@ -package Deadlock_11; - -import java.util.Random; -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 - */ -@SuppressWarnings("InfiniteLoopStatement") -public class Runner { - - private Account acc1 = new Account(); - private Account acc2 = new Account(); - private Lock lock1 = new ReentrantLock(); - private Lock lock2 = new ReentrantLock(); - - //don't hold several locks at once. If you do, always acquire the locks in the same order - //try to get the both locks - private void acquireLocks(Lock firstLock, Lock secondLock) throws InterruptedException { - while (true) { - // Acquire locks - boolean gotFirstLock = false; - boolean gotSecondLock = false; - try { - /** - * tryLock() which will only acquire a lock if it’s available - * and not already acquired by another thread and tryLock(long - * time,TimeUnit unit), which will try to acquire a lock and, if - * it's unavailable wait for the specified timer to expire - * before giving up - */ - gotFirstLock = firstLock.tryLock(); - gotSecondLock = secondLock.tryLock(); - } finally { - if (gotFirstLock && gotSecondLock) return; - else if (gotFirstLock) firstLock.unlock(); - else if (gotSecondLock) secondLock.unlock(); - } - // Locks not acquired - Thread.sleep(1); - } - } - - //firstThread runs - public void firstThread() throws InterruptedException { - Random random = new Random(); - for (int i = 0; i < 10000; i++) { - acquireLocks(lock1, lock2); - try { - Account.transfer(acc1, acc2, random.nextInt(100)); - } finally { - lock1.unlock(); - lock2.unlock(); - } - } - } - - //SecondThread runs - public void secondThread() throws InterruptedException { - Random random = new Random(); - for (int i = 0; i < 10000; i++) { - acquireLocks(lock2, lock1); - try { - Account.transfer(acc2, acc1, random.nextInt(100)); - } finally { - lock1.unlock(); - lock2.unlock(); - } - } - } - - //When both threads finish execution, finished runs - public void finished() { - System.out.println("Account 1 balance: " + acc1.getBalance()); - System.out.println("Account 2 balance: " + acc2.getBalance()); - System.out.println("Total balance: " + (acc1.getBalance() + acc2.getBalance())); - } -} +package Deadlock_11; + +import java.util.Random; +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 + */ +@SuppressWarnings("InfiniteLoopStatement") +public class Runner { + + private Account acc1 = new Account(); + private Account acc2 = new Account(); + private Lock lock1 = new ReentrantLock(); + private Lock lock2 = new ReentrantLock(); + + //don't hold several locks at once. If you do, always acquire the locks in the same order + //try to get the both locks + private void acquireLocks(Lock firstLock, Lock secondLock) throws InterruptedException { + while (true) { + // Acquire locks + boolean gotFirstLock = false; + boolean gotSecondLock = false; + try { + /** + * tryLock() which will only acquire a lock if it’s available + * and not already acquired by another thread and tryLock(long + * time,TimeUnit unit), which will try to acquire a lock and, if + * it's unavailable wait for the specified timer to expire + * before giving up + */ + gotFirstLock = firstLock.tryLock(); + gotSecondLock = secondLock.tryLock(); + } finally { + if (gotFirstLock && gotSecondLock) return; + else if (gotFirstLock) firstLock.unlock(); + else if (gotSecondLock) secondLock.unlock(); + } + // Locks not acquired + Thread.sleep(1); + } + } + + //firstThread runs + public void firstThread() throws InterruptedException { + Random random = new Random(); + for (int i = 0; i < 10000; i++) { + acquireLocks(lock1, lock2); + try { + Account.transfer(acc1, acc2, random.nextInt(100)); + } finally { + lock1.unlock(); + lock2.unlock(); + } + } + } + + //SecondThread runs + public void secondThread() throws InterruptedException { + Random random = new Random(); + for (int i = 0; i < 10000; i++) { + acquireLocks(lock2, lock1); + try { + Account.transfer(acc2, acc1, random.nextInt(100)); + } finally { + lock1.unlock(); + lock2.unlock(); + } + } + } + + //When both threads finish execution, finished runs + public void finished() { + System.out.println("Account 1 balance: " + acc1.getBalance()); + System.out.println("Account 2 balance: " + acc2.getBalance()); + System.out.println("Total balance: " + (acc1.getBalance() + acc2.getBalance())); + } +} diff --git a/JavaMultiThreadingCodes/src/Deadlock_11/SimpleDeadLock.java b/src/Deadlock_11/SimpleDeadLock.java similarity index 96% rename from JavaMultiThreadingCodes/src/Deadlock_11/SimpleDeadLock.java rename to src/Deadlock_11/SimpleDeadLock.java index 9ad7f65..2decfac 100644 --- a/JavaMultiThreadingCodes/src/Deadlock_11/SimpleDeadLock.java +++ b/src/Deadlock_11/SimpleDeadLock.java @@ -1,57 +1,57 @@ -package Deadlock_11; - -/** - * Source: http://www.herongyang.com/Java/Deadlock-What-Is-Deadlock.html - *

- * 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. - * - * @author Z.B. Celik - */ -public class SimpleDeadLock { - - public static final Object lock1 = new Object(); - public static final Object lock2 = new Object(); - private int index; - - public static void main(String[] a) { - Thread t1 = new Thread1(); - Thread t2 = new Thread2(); - t1.start(); - t2.start(); - } - - private static class Thread1 extends Thread { - - public void run() { - synchronized (lock1) { - System.out.println("Thread 1: Holding lock 1..."); - try { - Thread.sleep(10); - } catch (InterruptedException ignored) {} - System.out.println("Thread 1: Waiting for lock 2..."); - synchronized (lock2) { - System.out.println("Thread 2: Holding lock 1 & 2..."); - } - } - } - } - - private static class Thread2 extends Thread { - - public void run() { - synchronized (lock2) { - System.out.println("Thread 2: Holding lock 2..."); - try { - Thread.sleep(10); - } catch (InterruptedException ignored) {} - System.out.println("Thread 2: Waiting for lock 1..."); - synchronized (lock1) { - System.out.println("Thread 2: Holding lock 2 & 1..."); - } - } - } - } -} +package Deadlock_11; + +/** + * Source: http://www.herongyang.com/Java/Deadlock-What-Is-Deadlock.html + *

+ * 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. + * + * @author Z.B. Celik + */ +public class SimpleDeadLock { + + public static final Object lock1 = new Object(); + public static final Object lock2 = new Object(); + private int index; + + public static void main(String[] a) { + Thread t1 = new Thread1(); + Thread t2 = new Thread2(); + t1.start(); + t2.start(); + } + + private static class Thread1 extends Thread { + + public void run() { + synchronized (lock1) { + System.out.println("Thread 1: Holding lock 1..."); + try { + Thread.sleep(10); + } catch (InterruptedException ignored) {} + System.out.println("Thread 1: Waiting for lock 2..."); + synchronized (lock2) { + System.out.println("Thread 2: Holding lock 1 & 2..."); + } + } + } + } + + private static class Thread2 extends Thread { + + public void run() { + synchronized (lock2) { + System.out.println("Thread 2: Holding lock 2..."); + try { + Thread.sleep(10); + } 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/InterruptingThreads14/App.java b/src/InterruptingThreads14/App.java similarity index 97% rename from JavaMultiThreadingCodes/src/InterruptingThreads14/App.java rename to src/InterruptingThreads14/App.java index a843f1e..f7602dd 100644 --- a/JavaMultiThreadingCodes/src/InterruptingThreads14/App.java +++ b/src/InterruptingThreads14/App.java @@ -1,74 +1,74 @@ -package InterruptingThreads14; - -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 - * 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/ - * - *
- * also freely available at - * - * https://www.udemy.com/java-multithreading/?couponCode=FREE - * - * - * @author Z.B. Celik - */ -public class App { - - public static void main(String[] args) throws InterruptedException { - - System.out.println("Starting."); - - ExecutorService executor = Executors.newCachedThreadPool(); - - Future fu = executor.submit(new Callable() { - - @Override - public Void call() throws Exception { - - for (int i = 0; i < 1E8; i++) { - if (Thread.currentThread().isInterrupted()) { - System.out.printf("Interrupted at %d !!!", i); - break; - } - } - - 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); - System.out.println("Finished."); - } - -} +package InterruptingThreads14; + +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 + * 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/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * + * @author Z.B. Celik + */ +public class App { + + public static void main(String[] args) throws InterruptedException { + + System.out.println("Starting."); + + ExecutorService executor = Executors.newCachedThreadPool(); + + Future fu = executor.submit(new Callable() { + + @Override + public Void call() throws Exception { + + for (int i = 0; i < 1E8; i++) { + if (Thread.currentThread().isInterrupted()) { + System.out.printf("Interrupted at %d !!!", i); + break; + } + } + + 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); + System.out.println("Finished."); + } + +} diff --git a/JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java b/src/JoiningAndSynchronizeThreads_3/Worker.java similarity index 100% rename from JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java rename to src/JoiningAndSynchronizeThreads_3/Worker.java diff --git a/JavaMultiThreadingCodes/src/LockObjects_4/App.java b/src/LockObjects_4/App.java similarity index 96% rename from JavaMultiThreadingCodes/src/LockObjects_4/App.java rename to src/LockObjects_4/App.java index c7941fb..4deb88f 100644 --- a/JavaMultiThreadingCodes/src/LockObjects_4/App.java +++ b/src/LockObjects_4/App.java @@ -1,26 +1,26 @@ -package LockObjects_4; - -/** - * 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 App { - - public static void main(String[] args) { - System.out.println("Synchronized Objects: "); - Worker worker = new Worker(); - worker.main(); - System.out.println("Synchronized Methods: "); - WorkerMethodsSynchronized worker2 = new WorkerMethodsSynchronized(); - worker2.main(); - } -} +package LockObjects_4; + +/** + * 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 App { + + public static void main(String[] args) { + System.out.println("Synchronized Objects: "); + Worker worker = new Worker(); + worker.main(); + System.out.println("Synchronized Methods: "); + WorkerMethodsSynchronized worker2 = new WorkerMethodsSynchronized(); + worker2.main(); + } +} diff --git a/JavaMultiThreadingCodes/src/LockObjects_4/Worker.java b/src/LockObjects_4/Worker.java similarity index 96% rename from JavaMultiThreadingCodes/src/LockObjects_4/Worker.java rename to src/LockObjects_4/Worker.java index 70ad012..4235770 100644 --- a/JavaMultiThreadingCodes/src/LockObjects_4/Worker.java +++ b/src/LockObjects_4/Worker.java @@ -1,99 +1,99 @@ -package LockObjects_4; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -/** - * Multiple locks to speed up complex multi-threaded code. Define shared - * objects: list1 and list2 then synchronize these objects. Mainly discussing - * 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/ - * - *
- * also freely available at - * - * https://www.udemy.com/java-multithreading/?couponCode=FREE - * - * - * @author Z.B. Celik - */ -public class Worker { - - private Random random = new Random(); - - private final Object lock1 = new Object(); - private final Object lock2 = new Object(); - - private List list1 = new ArrayList<>(); - private List list2 = new ArrayList<>(); - - public void stageOne() { - - synchronized (lock1) { - try { - Thread.sleep(1); - } catch (InterruptedException e) { - //do your work here - e.printStackTrace(); - } - list1.add(random.nextInt(100)); - } - } - - public void stageTwo() { - synchronized (lock2) { - try { - Thread.sleep(1); - } catch (InterruptedException e) { - //do your work here - e.printStackTrace(); - } - list2.add(random.nextInt(100)); - } - - } - - public void process() { - for (int i = 0; i < 1000; i++) { - stageOne(); - stageTwo(); - } - } - - public void main() { - System.out.println("Starting ..."); - long start = System.currentTimeMillis(); - Thread t1 = new Thread(new Runnable() { - public void run() { - process(); - } - }); - - Thread t2 = new Thread(new Runnable() { - public void run() { - process(); - } - }); - - t1.start(); - t2.start(); - - try { - t1.join(); - t2.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - long end = System.currentTimeMillis(); - - System.out.println("Time taken: " + (end - start)); - System.out.println("List1: " + list1.size() + "; List2: " + list2.size()); - } -} +package LockObjects_4; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +/** + * Multiple locks to speed up complex multi-threaded code. Define shared + * objects: list1 and list2 then synchronize these objects. Mainly discussing + * 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/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * + * @author Z.B. Celik + */ +public class Worker { + + private Random random = new Random(); + + private final Object lock1 = new Object(); + private final Object lock2 = new Object(); + + private List list1 = new ArrayList<>(); + private List list2 = new ArrayList<>(); + + public void stageOne() { + + synchronized (lock1) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + //do your work here + e.printStackTrace(); + } + list1.add(random.nextInt(100)); + } + } + + public void stageTwo() { + synchronized (lock2) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + //do your work here + e.printStackTrace(); + } + list2.add(random.nextInt(100)); + } + + } + + public void process() { + for (int i = 0; i < 1000; i++) { + stageOne(); + stageTwo(); + } + } + + public void main() { + System.out.println("Starting ..."); + long start = System.currentTimeMillis(); + Thread t1 = new Thread(new Runnable() { + public void run() { + process(); + } + }); + + Thread t2 = new Thread(new Runnable() { + public void run() { + process(); + } + }); + + t1.start(); + t2.start(); + + try { + t1.join(); + t2.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + long end = System.currentTimeMillis(); + + System.out.println("Time taken: " + (end - start)); + System.out.println("List1: " + list1.size() + "; List2: " + list2.size()); + } +} diff --git a/JavaMultiThreadingCodes/src/LockObjects_4/WorkerMethodsSynchronized.java b/src/LockObjects_4/WorkerMethodsSynchronized.java similarity index 96% rename from JavaMultiThreadingCodes/src/LockObjects_4/WorkerMethodsSynchronized.java rename to src/LockObjects_4/WorkerMethodsSynchronized.java index c01b492..62df970 100644 --- a/JavaMultiThreadingCodes/src/LockObjects_4/WorkerMethodsSynchronized.java +++ b/src/LockObjects_4/WorkerMethodsSynchronized.java @@ -1,94 +1,94 @@ -package LockObjects_4; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -/** - * Multiple locks to speed up complex multi-threaded code. Define shared - * objects: list1 and list2 then synchronize these objects. Mainly discussing - * 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/ - * - *
- * also freely available at - * - * https://www.udemy.com/java-multithreading/?couponCode=FREE - * - * - * @author Z.B. Celik - */ -public class WorkerMethodsSynchronized { - - private Random random = new Random(); - - private List list1 = new ArrayList<>(); - private List list2 = new ArrayList<>(); - - /** - * synchronized, methods use different data (list1 list2) so by synchronized - * methods if one thread runs the stageOne other thread cannot run stageTwo - * at the same time because that same locks are used. Solution is using two - * lock Object for two shared data. - */ - public synchronized void stageOne() { - try { - //do your work here - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - list1.add(random.nextInt(100)); - } - - public synchronized void stageTwo() { - try { - //do your work here - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - list2.add(random.nextInt(100)); - } - - public void process() { - for (int i = 0; i < 1000; i++) { - stageOne(); - stageTwo(); - } - } - - public void main() { - System.out.println("Starting ..."); - long start = System.currentTimeMillis(); - Thread t1 = new Thread(new Runnable() { - public void run() { - process(); - } - }); - - Thread t2 = new Thread(new Runnable() { - public void run() { - process(); - } - }); - - t1.start(); - t2.start(); - - try { - t1.join(); - t2.join(); - } catch (InterruptedException ignored) {} - - long end = System.currentTimeMillis(); - - System.out.println("Time taken: " + (end - start)); - System.out.println("List1: " + list1.size() + "; List2: " + list2.size()); - } -} +package LockObjects_4; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +/** + * Multiple locks to speed up complex multi-threaded code. Define shared + * objects: list1 and list2 then synchronize these objects. Mainly discussing + * 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/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * + * @author Z.B. Celik + */ +public class WorkerMethodsSynchronized { + + private Random random = new Random(); + + private List list1 = new ArrayList<>(); + private List list2 = new ArrayList<>(); + + /** + * synchronized, methods use different data (list1 list2) so by synchronized + * methods if one thread runs the stageOne other thread cannot run stageTwo + * at the same time because that same locks are used. Solution is using two + * lock Object for two shared data. + */ + public synchronized void stageOne() { + try { + //do your work here + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + list1.add(random.nextInt(100)); + } + + public synchronized void stageTwo() { + try { + //do your work here + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + list2.add(random.nextInt(100)); + } + + public void process() { + for (int i = 0; i < 1000; i++) { + stageOne(); + stageTwo(); + } + } + + public void main() { + System.out.println("Starting ..."); + long start = System.currentTimeMillis(); + Thread t1 = new Thread(new Runnable() { + public void run() { + process(); + } + }); + + Thread t2 = new Thread(new Runnable() { + public void run() { + process(); + } + }); + + t1.start(); + t2.start(); + + try { + t1.join(); + t2.join(); + } catch (InterruptedException ignored) {} + + long end = System.currentTimeMillis(); + + System.out.println("Time taken: " + (end - start)); + System.out.println("List1: " + list1.size() + "; List2: " + list2.size()); + } +} diff --git a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/App.java b/src/LowLevelProducerConsumer_9/App.java similarity index 96% rename from JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/App.java rename to src/LowLevelProducerConsumer_9/App.java index aabbfd3..518b39c 100644 --- a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/App.java +++ b/src/LowLevelProducerConsumer_9/App.java @@ -1,55 +1,55 @@ -package LowLevelProducerConsumer_9; - -/** - * 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 {@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/ - * - *
- * also freely available at - * - * https://www.udemy.com/java-multithreading/?couponCode=FREE - * - * - * @author Z.B. Celik - */ -public class App { - - public static void main(String[] args) throws InterruptedException { - final Processor processor = new Processor(); - Thread t1 = new Thread(new Runnable() { - @Override - public void run() { - try { - processor.produce(); - } catch (InterruptedException ignored) {} - } - }); - - Thread t2 = new Thread(new Runnable() { - @Override - public void run() { - try { - processor.consume(); - } catch (InterruptedException ignored) {} - } - }); - - t1.start(); - t2.start(); -// t1.join(); -// t2.join(); - - // Pause for 30 seconds and force quitting the app (because we're - // looping infinitely) - Thread.sleep(30000); - System.exit(0); - } -} +package LowLevelProducerConsumer_9; + +/** + * 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 {@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/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * + * @author Z.B. Celik + */ +public class App { + + public static void main(String[] args) throws InterruptedException { + final Processor processor = new Processor(); + Thread t1 = new Thread(new Runnable() { + @Override + public void run() { + try { + processor.produce(); + } catch (InterruptedException ignored) {} + } + }); + + Thread t2 = new Thread(new Runnable() { + @Override + public void run() { + try { + processor.consume(); + } catch (InterruptedException ignored) {} + } + }); + + t1.start(); + t2.start(); +// 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/src/LowLevelProducerConsumer_9/Processor.java similarity index 96% rename from JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java rename to src/LowLevelProducerConsumer_9/Processor.java index e061c1d..0bd20cd 100644 --- a/JavaMultiThreadingCodes/src/LowLevelProducerConsumer_9/Processor.java +++ b/src/LowLevelProducerConsumer_9/Processor.java @@ -1,59 +1,59 @@ -package LowLevelProducerConsumer_9; - -import java.util.LinkedList; -import java.util.Random; - -/** - * 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 Processor { - - private LinkedList list = new LinkedList<>(); - private final int LIMIT = 10; - private final Object lock = new Object(); - - public void produce() throws InterruptedException { - int value = 0; - while (true) { - synchronized (lock) { - //whenever the thread is notified starts again from the loop - while (list.size() == LIMIT) { - lock.wait();// wait() is also true - } - list.add(value); - - System.out.println("Producer added: " + value + " queue size is " + list.size()); - value++; - lock.notify(); - } - } - } - - public void consume() throws InterruptedException { - Random random = new Random(); - while (true) { - synchronized (lock) { - while (list.size() == 0) { - lock.wait(); - } - - int value = list.removeFirst(); - System.out.print("Removed value by consumer is: " + value); - System.out.println(" Now list size is: " + list.size()); - lock.notify(); - } - Thread.sleep(random.nextInt(1000)); //force producer fill the queue to LIMIT_SIZE - } - } -} +package LowLevelProducerConsumer_9; + +import java.util.LinkedList; +import java.util.Random; + +/** + * 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 Processor { + + private LinkedList list = new LinkedList<>(); + private final int LIMIT = 10; + private final Object lock = new Object(); + + public void produce() throws InterruptedException { + int value = 0; + while (true) { + synchronized (lock) { + //whenever the thread is notified starts again from the loop + while (list.size() == LIMIT) { + lock.wait();// wait() is also true + } + list.add(value); + + System.out.println("Producer added: " + value + " queue size is " + list.size()); + value++; + lock.notify(); + } + } + } + + public void consume() throws InterruptedException { + Random random = new Random(); + while (true) { + synchronized (lock) { + while (list.size() == 0) { + lock.wait(); + } + + int value = list.removeFirst(); + System.out.print("Removed value by consumer is: " + value); + System.out.println(" Now list size is: " + list.size()); + lock.notify(); + } + Thread.sleep(random.nextInt(1000)); //force producer fill the queue to LIMIT_SIZE + } + } +} diff --git a/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java b/src/ProducerConsumer_7/App.java similarity index 97% rename from JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java rename to src/ProducerConsumer_7/App.java index b064da4..ae0e416 100644 --- a/JavaMultiThreadingCodes/src/ProducerConsumer_7/App.java +++ b/src/ProducerConsumer_7/App.java @@ -1,90 +1,90 @@ -package ProducerConsumer_7; - -/** - * 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/ - * - *
- * also freely available at - * - * https://www.udemy.com/java-multithreading/?couponCode=FREE - * - * - * @author Z.B. Celik - */ -import java.util.Random; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; - -@SuppressWarnings("InfiniteLoopStatement") -public class App { - - /** - * 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 - * {@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); - - public static void main(String[] args) throws InterruptedException { - - Thread t1 = new Thread(new Runnable() { - public void run() { - try { - producer(); - } catch (InterruptedException ignored) {} - } - }); - - Thread t2 = new Thread(new Runnable() { - public void run() { - try { - consumer(); - } catch (InterruptedException ignored) {} - } - }); - t1.start(); - t2.start(); -// 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 { - Random random = new Random(); - while (true) {//loop indefinitely - queue.put(random.nextInt(100));//if queue is full (10) waits - } - } - - private static void consumer() throws InterruptedException { - Random random = new Random(); - while (true) { - 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()); - } - } - } -} +package ProducerConsumer_7; + +/** + * 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/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * + * @author Z.B. Celik + */ +import java.util.Random; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; + +@SuppressWarnings("InfiniteLoopStatement") +public class App { + + /** + * 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 + * {@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); + + public static void main(String[] args) throws InterruptedException { + + Thread t1 = new Thread(new Runnable() { + public void run() { + try { + producer(); + } catch (InterruptedException ignored) {} + } + }); + + Thread t2 = new Thread(new Runnable() { + public void run() { + try { + consumer(); + } catch (InterruptedException ignored) {} + } + }); + t1.start(); + t2.start(); +// 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 { + Random random = new Random(); + while (true) {//loop indefinitely + queue.put(random.nextInt(100));//if queue is full (10) waits + } + } + + private static void consumer() throws InterruptedException { + Random random = new Random(); + while (true) { + 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()); + } + } + } +} diff --git a/JavaMultiThreadingCodes/src/ReentrantLocks_10/App.java b/src/ReentrantLocks_10/App.java similarity index 97% rename from JavaMultiThreadingCodes/src/ReentrantLocks_10/App.java rename to src/ReentrantLocks_10/App.java index 845fbe7..b6fe5fc 100644 --- a/JavaMultiThreadingCodes/src/ReentrantLocks_10/App.java +++ b/src/ReentrantLocks_10/App.java @@ -1,98 +1,98 @@ -package ReentrantLocks_10; - -/** - * 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: - * http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html - * - *

- * {@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 {@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/ - * - *
- * also freely available at - * - * https://www.udemy.com/java-multithreading/?couponCode=FREE - * - * - * @author Z.B. Celik - */ -public class App { - - public static void main(String[] args) throws Exception { - final Runner runner = new Runner(); - Thread t1 = new Thread(new Runnable() { - public void run() { - try { - runner.firstThread(); - } catch (InterruptedException ignored) { - } - } - }); - - Thread t2 = new Thread(new Runnable() { - public void run() { - try { - runner.secondThread(); - } catch (InterruptedException ignored) { - } - } - }); - - t1.start(); - t2.start(); - t1.join(); - t2.join(); - runner.finished(); - } - -} +package ReentrantLocks_10; + +/** + * 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: + * http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html + * + *

+ * {@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 {@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/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * + * @author Z.B. Celik + */ +public class App { + + public static void main(String[] args) throws Exception { + final Runner runner = new Runner(); + Thread t1 = new Thread(new Runnable() { + public void run() { + try { + runner.firstThread(); + } catch (InterruptedException ignored) { + } + } + }); + + Thread t2 = new Thread(new Runnable() { + public void run() { + try { + runner.secondThread(); + } catch (InterruptedException ignored) { + } + } + }); + + t1.start(); + t2.start(); + t1.join(); + t2.join(); + runner.finished(); + } + +} diff --git a/JavaMultiThreadingCodes/src/ReentrantLocks_10/Runner.java b/src/ReentrantLocks_10/Runner.java similarity index 97% rename from JavaMultiThreadingCodes/src/ReentrantLocks_10/Runner.java rename to src/ReentrantLocks_10/Runner.java index b97b4af..17f215f 100644 --- a/JavaMultiThreadingCodes/src/ReentrantLocks_10/Runner.java +++ b/src/ReentrantLocks_10/Runner.java @@ -1,92 +1,92 @@ -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 - *

- * {@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 {@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. - *

- * {@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) - *

- * {@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 - * {@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 - * - * - * @author Z.B. Celik - */ -public class Runner { - - private int count = 0; - private Lock lock = new ReentrantLock(); - private Condition cond = lock.newCondition(); - - private void increment() { - for (int i = 0; i < 10000; i++) { - count++; - } - } - - public void firstThread() throws InterruptedException { - lock.lock(); - System.out.println("Waiting ...."); - cond.await(); - System.out.println("Woken up!"); - try { - increment(); - } finally { - lock.unlock(); - } - } - - public void secondThread() throws InterruptedException { - Thread.sleep(1000); - lock.lock(); - System.out.println("Press the return key!"); - new Scanner(System.in).nextLine(); - System.out.println("Got return key!"); - cond.signal(); - try { - increment(); - } finally { - //should be written to unlock Thread whenever signal() is called - lock.unlock(); - } - } - - public void finished() { - System.out.println("Count is: " + count); - } -} +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 + *

+ * {@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 {@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. + *

+ * {@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) + *

+ * {@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 + * {@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 + * + * + * @author Z.B. Celik + */ +public class Runner { + + private int count = 0; + private Lock lock = new ReentrantLock(); + private Condition cond = lock.newCondition(); + + private void increment() { + for (int i = 0; i < 10000; i++) { + count++; + } + } + + public void firstThread() throws InterruptedException { + lock.lock(); + System.out.println("Waiting ...."); + cond.await(); + System.out.println("Woken up!"); + try { + increment(); + } finally { + lock.unlock(); + } + } + + public void secondThread() throws InterruptedException { + Thread.sleep(1000); + lock.lock(); + System.out.println("Press the return key!"); + new Scanner(System.in).nextLine(); + System.out.println("Got return key!"); + cond.signal(); + try { + increment(); + } finally { + //should be written to unlock Thread whenever signal() is called + lock.unlock(); + } + } + + public void finished() { + System.out.println("Count is: " + count); + } +} diff --git a/JavaMultiThreadingCodes/src/Semaphores_12/App.java b/src/Semaphores_12/App.java similarity index 97% rename from JavaMultiThreadingCodes/src/Semaphores_12/App.java rename to src/Semaphores_12/App.java index 154da74..0da08cd 100644 --- a/JavaMultiThreadingCodes/src/Semaphores_12/App.java +++ b/src/Semaphores_12/App.java @@ -1,66 +1,66 @@ -package Semaphores_12; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -/** - * {@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 - * can unlock from other threads. - *
- * Source: - * - * http://stackoverflow.com/questions/771347/what-is-mutex-and-semaphore-in-java-what-is-the-main-difference - * - *

- * 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. - * 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/ - * - *
- * also freely available at - * - * https://www.udemy.com/java-multithreading/?couponCode=FREE - * - * - * @author Z.B. Celik - */ -public class App { - - public static void main(String[] args) throws Exception { - ExecutorService executor = Executors.newCachedThreadPool(); - - for (int i = 0; i < 20; i++) { //200 hundred times will be called - executor.submit(new Runnable() { - public void run() { - Connectionn.getInstance().connect(); - } - }); - } - - executor.shutdown(); - executor.awaitTermination(1, TimeUnit.DAYS); - } -} +package Semaphores_12; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * {@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 + * can unlock from other threads. + *
+ * Source: + * + * http://stackoverflow.com/questions/771347/what-is-mutex-and-semaphore-in-java-what-is-the-main-difference + * + *

+ * 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. + * 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/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * + * @author Z.B. Celik + */ +public class App { + + public static void main(String[] args) throws Exception { + ExecutorService executor = Executors.newCachedThreadPool(); + + for (int i = 0; i < 20; i++) { //200 hundred times will be called + executor.submit(new Runnable() { + public void run() { + Connectionn.getInstance().connect(); + } + }); + } + + executor.shutdown(); + executor.awaitTermination(1, TimeUnit.DAYS); + } +} diff --git a/JavaMultiThreadingCodes/src/Semaphores_12/Connection.java b/src/Semaphores_12/Connection.java similarity index 97% rename from JavaMultiThreadingCodes/src/Semaphores_12/Connection.java rename to src/Semaphores_12/Connection.java index 88836e2..11dcf70 100644 --- a/JavaMultiThreadingCodes/src/Semaphores_12/Connection.java +++ b/src/Semaphores_12/Connection.java @@ -1,82 +1,82 @@ -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 Connection { - - private static Connection instance = new Connection(); -/* - 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; - - private Connection() { - } - - public static Connection getInstance() { - return instance; - } - - public void connect() { - 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 - doConnect(); - - } catch (InterruptedException ignored) { - } finally { - //release permit, increase the sem value and activate waiting thread - sem.release(); - } - } - - public void doConnect() { - synchronized (this) { //atomic - connections++; - System.out.println("Current connections (max 10 allowed): " + connections); - } - try { - //do your job - System.out.println("Working on connections " + Thread.currentThread().getName()); - Thread.sleep(2000); - } catch (InterruptedException ignored) {} - //when exit doConnect method decrement number of connections - synchronized (this) {//atomic - connections--; - System.out.println("I'm done " + Thread.currentThread().getName() + " Connection is released , connection count: " + connections); - } - } -} +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 Connection { + + private static Connection instance = new Connection(); +/* + 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; + + private Connection() { + } + + public static Connection getInstance() { + return instance; + } + + public void connect() { + 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 + doConnect(); + + } catch (InterruptedException ignored) { + } finally { + //release permit, increase the sem value and activate waiting thread + sem.release(); + } + } + + public void doConnect() { + synchronized (this) { //atomic + connections++; + System.out.println("Current connections (max 10 allowed): " + connections); + } + try { + //do your job + System.out.println("Working on connections " + Thread.currentThread().getName()); + Thread.sleep(2000); + } catch (InterruptedException ignored) {} + //when exit doConnect method decrement number of connections + synchronized (this) {//atomic + connections--; + System.out.println("I'm done " + Thread.currentThread().getName() + " Connection is released , connection count: " + connections); + } + } +} diff --git a/JavaMultiThreadingCodes/src/Semaphores_12/Connectionn.java b/src/Semaphores_12/Connectionn.java similarity index 97% rename from JavaMultiThreadingCodes/src/Semaphores_12/Connectionn.java rename to src/Semaphores_12/Connectionn.java index 0171cc7..a24d16c 100644 --- a/JavaMultiThreadingCodes/src/Semaphores_12/Connectionn.java +++ b/src/Semaphores_12/Connectionn.java @@ -1,73 +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(); - } - } -} +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(); + } + } +} diff --git a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java b/src/StartingThreads_1/ApplicationAnonymous.java similarity index 96% rename from JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java rename to src/StartingThreads_1/ApplicationAnonymous.java index 8e11f90..674c337 100644 --- a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationAnonymous.java +++ b/src/StartingThreads_1/ApplicationAnonymous.java @@ -1,37 +1,37 @@ -package StartingThreads_1; - -/** - * Starting threads using the Thread constructor with anonymous classes - *

- * 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 ApplicationAnonymous { - - public static void main(String[] args) { - Thread thread1 = new Thread(new Runnable() { - @Override - public void run() { - for (int i = 0; i < 5; i++) { - System.out.println("Hello: " + i + " Thread: " + Thread.currentThread().getName()); - - try { - Thread.sleep(100); - } catch (InterruptedException ignored) {} - } - } - }); - - thread1.start(); - } - -} +package StartingThreads_1; + +/** + * Starting threads using the Thread constructor with anonymous classes + *

+ * 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 ApplicationAnonymous { + + public static void main(String[] args) { + Thread thread1 = new Thread(new Runnable() { + @Override + public void run() { + for (int i = 0; i < 5; i++) { + System.out.println("Hello: " + i + " Thread: " + Thread.currentThread().getName()); + + try { + Thread.sleep(100); + } catch (InterruptedException ignored) {} + } + } + }); + + thread1.start(); + } + +} diff --git a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationExtends.java b/src/StartingThreads_1/ApplicationExtends.java similarity index 100% rename from JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationExtends.java rename to src/StartingThreads_1/ApplicationExtends.java diff --git a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationRunnable.java b/src/StartingThreads_1/ApplicationRunnable.java similarity index 96% rename from JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationRunnable.java rename to src/StartingThreads_1/ApplicationRunnable.java index a7561e3..6872101 100644 --- a/JavaMultiThreadingCodes/src/StartingThreads_1/ApplicationRunnable.java +++ b/src/StartingThreads_1/ApplicationRunnable.java @@ -1,43 +1,43 @@ -package StartingThreads_1; - -/** - * 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 - * - * - * @author Z.B. Celik - */ -class RunnerRunnable implements Runnable { - - @Override - public void run() { - for (int i = 0; i < 5; i++) { - System.out.println("Hello: " + i + " Thread: " + Thread.currentThread().getName()); - - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } -} - -public class ApplicationRunnable { - - public static void main(String[] args) { - Thread thread1 = new Thread(new RunnerRunnable()); - Thread thread2 = new Thread(new RunnerRunnable()); - thread1.start(); - thread2.start(); - } - -} +package StartingThreads_1; + +/** + * 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 + * + * + * @author Z.B. Celik + */ +class RunnerRunnable implements Runnable { + + @Override + public void run() { + for (int i = 0; i < 5; i++) { + System.out.println("Hello: " + i + " Thread: " + Thread.currentThread().getName()); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } +} + +public class ApplicationRunnable { + + public static void main(String[] args) { + Thread thread1 = new Thread(new RunnerRunnable()); + Thread thread2 = new Thread(new RunnerRunnable()); + thread1.start(); + thread2.start(); + } + +} diff --git a/JavaMultiThreadingCodes/src/ThreadPools_5/App.java b/src/ThreadPools_5/App.java similarity index 96% rename from JavaMultiThreadingCodes/src/ThreadPools_5/App.java rename to src/ThreadPools_5/App.java index 3cc0c33..fc55284 100644 --- a/JavaMultiThreadingCodes/src/ThreadPools_5/App.java +++ b/src/ThreadPools_5/App.java @@ -1,58 +1,58 @@ -package ThreadPools_5; - -/** - * ThreadPool ("number of workers in a factory") - *

- * 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.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -class Processor implements Runnable { - - private int id; - - public Processor(int id) { - this.id = id; - } - - public void run() { - System.out.println("Starting: " + id); - try { - Thread.sleep(5000); - } catch (InterruptedException ignored) { - } - System.out.println("Completed: " + id); - } -} - -public class App { - - public static void main(String[] args) { - /** - * Created 2 threads, and assign tasks (Processor(i).run) to the threads - */ - ExecutorService executor = Executors.newFixedThreadPool(2);//2 Threads - for (int i = 0; i < 2; i++) { // call the (Processor(i).run) 2 times with 2 threads - executor.submit(new Processor(i)); - } - executor.shutdown(); - System.out.println("All tasks submitted."); - try { - executor.awaitTermination(1, TimeUnit.DAYS); - } catch (InterruptedException ignored) { - } - System.out.println("All tasks completed."); - } -} +package ThreadPools_5; + +/** + * ThreadPool ("number of workers in a factory") + *

+ * 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.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +class Processor implements Runnable { + + private int id; + + public Processor(int id) { + this.id = id; + } + + public void run() { + System.out.println("Starting: " + id); + try { + Thread.sleep(5000); + } catch (InterruptedException ignored) { + } + System.out.println("Completed: " + id); + } +} + +public class App { + + public static void main(String[] args) { + /** + * Created 2 threads, and assign tasks (Processor(i).run) to the threads + */ + ExecutorService executor = Executors.newFixedThreadPool(2);//2 Threads + for (int i = 0; i < 2; i++) { // call the (Processor(i).run) 2 times with 2 threads + executor.submit(new Processor(i)); + } + executor.shutdown(); + System.out.println("All tasks submitted."); + try { + executor.awaitTermination(1, TimeUnit.DAYS); + } catch (InterruptedException ignored) { + } + System.out.println("All tasks completed."); + } +} diff --git a/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java b/src/ThreadPools_5/WorkerThreadPool.java similarity index 97% rename from JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java rename to src/ThreadPools_5/WorkerThreadPool.java index 6251a4f..2dd99e3 100644 --- a/JavaMultiThreadingCodes/src/ThreadPools_5/WorkerThreadPool.java +++ b/src/ThreadPools_5/WorkerThreadPool.java @@ -1,96 +1,96 @@ -package ThreadPools_5; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -/** - * 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 - * - * - * @author Z.B. Celik - */ -class Worker implements Runnable { - - private Random random = new Random(); - private final Object lock1 = new Object(); - private final Object lock2 = new Object(); - public List list1 = new ArrayList<>(); - public List list2 = new ArrayList<>(); - - @Override - public void run() { - process(); - } - - public void process() { - for (int i = 0; i < 1000; i++) { - stageOne(); - stageTwo(); - } - } - - public void stageOne() { - synchronized (lock1) { - try { - Thread.sleep(1); - } catch (InterruptedException e) { - //do your work here - e.printStackTrace(); - } - list1.add(random.nextInt(100)); - } - } - - public void stageTwo() { - synchronized (lock2) { - try { - Thread.sleep(1); - } catch (InterruptedException e) { - //do your work here - e.printStackTrace(); - } - list2.add(random.nextInt(100)); - } - } -} - -public class WorkerThreadPool { - - public static void main(String[] args) { - 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 - executor.submit(worker); - } - executor.shutdown(); //prevents new tasks from being accepted by the ExecutorService - try { - 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). - } catch (InterruptedException ex) { - System.out.println(ex.getMessage()); - } - long end = System.currentTimeMillis(); - System.out.println("Time taken: " + (end - start)); - System.out.println("List1: " + worker.list1.size() + "; List2: " + worker.list2.size()); - } - -} +package ThreadPools_5; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * 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 + * + * + * @author Z.B. Celik + */ +class Worker implements Runnable { + + private Random random = new Random(); + private final Object lock1 = new Object(); + private final Object lock2 = new Object(); + public List list1 = new ArrayList<>(); + public List list2 = new ArrayList<>(); + + @Override + public void run() { + process(); + } + + public void process() { + for (int i = 0; i < 1000; i++) { + stageOne(); + stageTwo(); + } + } + + public void stageOne() { + synchronized (lock1) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + //do your work here + e.printStackTrace(); + } + list1.add(random.nextInt(100)); + } + } + + public void stageTwo() { + synchronized (lock2) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + //do your work here + e.printStackTrace(); + } + list2.add(random.nextInt(100)); + } + } +} + +public class WorkerThreadPool { + + public static void main(String[] args) { + 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 + executor.submit(worker); + } + executor.shutdown(); //prevents new tasks from being accepted by the ExecutorService + try { + 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). + } catch (InterruptedException ex) { + System.out.println(ex.getMessage()); + } + long end = System.currentTimeMillis(); + System.out.println("Time taken: " + (end - start)); + System.out.println("List1: " + worker.list1.size() + "; List2: " + worker.list2.size()); + } + +} diff --git a/JavaMultiThreadingCodes/src/VolatileKeyword_2/App.java b/src/VolatileKeyword_2/App.java similarity index 100% rename from JavaMultiThreadingCodes/src/VolatileKeyword_2/App.java rename to src/VolatileKeyword_2/App.java diff --git a/JavaMultiThreadingCodes/src/WaitAndNotify_8/App.java b/src/WaitAndNotify_8/App.java similarity index 96% rename from JavaMultiThreadingCodes/src/WaitAndNotify_8/App.java rename to src/WaitAndNotify_8/App.java index c6e2b07..bae8695 100644 --- a/JavaMultiThreadingCodes/src/WaitAndNotify_8/App.java +++ b/src/WaitAndNotify_8/App.java @@ -1,49 +1,49 @@ -package WaitAndNotify_8; - -/** - * {@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/ - * - *
- * also freely available at - * - * https://www.udemy.com/java-multithreading/?couponCode=FREE - * - * - * @author Z.B. Celik - */ -public class App { - - public static void main(String[] args) throws InterruptedException { - final Processor processor = new Processor(); - Thread t1 = new Thread(new Runnable() { - @Override - public void run() { - try { - processor.produce(); - } catch (InterruptedException ignored) {} - } - }); - - Thread t2 = new Thread(new Runnable() { - @Override - public void run() { - try { - processor.consume(); - } catch (InterruptedException ignored) {} - } - }); - - t1.start(); - t2.start(); - t1.join(); - t2.join(); - } -} +package WaitAndNotify_8; + +/** + * {@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/ + * + *
+ * also freely available at + * + * https://www.udemy.com/java-multithreading/?couponCode=FREE + * + * + * @author Z.B. Celik + */ +public class App { + + public static void main(String[] args) throws InterruptedException { + final Processor processor = new Processor(); + Thread t1 = new Thread(new Runnable() { + @Override + public void run() { + try { + processor.produce(); + } catch (InterruptedException ignored) {} + } + }); + + Thread t2 = new Thread(new Runnable() { + @Override + public void run() { + try { + processor.consume(); + } catch (InterruptedException ignored) {} + } + }); + + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } +} diff --git a/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java b/src/WaitAndNotify_8/BlockingQueueApp.java similarity index 97% rename from JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java rename to src/WaitAndNotify_8/BlockingQueueApp.java index 99f76ca..92bf447 100644 --- a/JavaMultiThreadingCodes/src/WaitAndNotify_8/BlockingQueueApp.java +++ b/src/WaitAndNotify_8/BlockingQueueApp.java @@ -1,137 +1,137 @@ -package WaitAndNotify_8; - -import java.util.LinkedList; -import java.util.Queue; -import java.util.Random; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * Source: - * 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 - * {@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 {@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 {@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. - *
- * But our thread will automatically release the lock temporarily while waiting. - * 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 {@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. - * - * - * @author Z.B. Celik - */ -//For the other version of the implementation please check -// LowLevelProducerConsumer_9.App -class BlockingQueue { - - private Queue queue = new LinkedList<>(); - private int capacity; - private Lock lock = new ReentrantLock(); - //condition variables - private Condition notFull = lock.newCondition(); - private Condition notEmpty = lock.newCondition(); - - public BlockingQueue(int capacity) { - this.capacity = capacity; - } - - public void put(T element) throws InterruptedException { - lock.lock(); - try { - while (queue.size() == capacity) { - System.out.println("queue is full cannot put"); - notFull.await(); //releases lock - } - - queue.add(element); - System.out.println("Added to the queue " + element); - notEmpty.signal(); //calls waiting thread on the same object - } finally { - lock.unlock(); - } - } - - public T take() throws InterruptedException { - lock.lock(); - try { - while (queue.isEmpty()) { - System.out.println("queue is empty, cannot take"); - notEmpty.await(); //releases lock - } - - T item = queue.remove(); - System.out.println("Removed to the queue " + item); - notFull.signal(); //calls waiting thread on same object - return item; - } finally { - lock.unlock(); - } - } -} - -@SuppressWarnings("InfiniteLoopStatement") -public class BlockingQueueApp { - - public static void main(String[] args) throws InterruptedException { - final BlockingQueue blockingQueue = new BlockingQueue<>(10); - final Random random = new Random(); - Thread t1 = new Thread(new Runnable() { - public void run() { - try { - while (true) { - blockingQueue.put(random.nextInt(10)); - } - } catch (InterruptedException ignored) {} - } - }); - - Thread t2 = new Thread(new Runnable() { - public void run() { - try { - Thread.sleep(1000);//wait for putting to the queue first - } catch (InterruptedException ex) { - System.out.println("Exception " + ex.getMessage()); - } - try { - while (true) { - blockingQueue.take(); - } - } catch (InterruptedException ignored) {} - } - }); - t1.start(); - t2.start(); - t1.join(); - t2.join(); - } -} +package WaitAndNotify_8; + +import java.util.LinkedList; +import java.util.Queue; +import java.util.Random; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * Source: + * 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 + * {@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 {@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 {@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. + *
+ * But our thread will automatically release the lock temporarily while waiting. + * 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 {@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. + * + * + * @author Z.B. Celik + */ +//For the other version of the implementation please check +// LowLevelProducerConsumer_9.App +class BlockingQueue { + + private Queue queue = new LinkedList<>(); + private int capacity; + private Lock lock = new ReentrantLock(); + //condition variables + private Condition notFull = lock.newCondition(); + private Condition notEmpty = lock.newCondition(); + + public BlockingQueue(int capacity) { + this.capacity = capacity; + } + + public void put(T element) throws InterruptedException { + lock.lock(); + try { + while (queue.size() == capacity) { + System.out.println("queue is full cannot put"); + notFull.await(); //releases lock + } + + queue.add(element); + System.out.println("Added to the queue " + element); + notEmpty.signal(); //calls waiting thread on the same object + } finally { + lock.unlock(); + } + } + + public T take() throws InterruptedException { + lock.lock(); + try { + while (queue.isEmpty()) { + System.out.println("queue is empty, cannot take"); + notEmpty.await(); //releases lock + } + + T item = queue.remove(); + System.out.println("Removed to the queue " + item); + notFull.signal(); //calls waiting thread on same object + return item; + } finally { + lock.unlock(); + } + } +} + +@SuppressWarnings("InfiniteLoopStatement") +public class BlockingQueueApp { + + public static void main(String[] args) throws InterruptedException { + final BlockingQueue blockingQueue = new BlockingQueue<>(10); + final Random random = new Random(); + Thread t1 = new Thread(new Runnable() { + public void run() { + try { + while (true) { + blockingQueue.put(random.nextInt(10)); + } + } catch (InterruptedException ignored) {} + } + }); + + Thread t2 = new Thread(new Runnable() { + public void run() { + try { + Thread.sleep(1000);//wait for putting to the queue first + } catch (InterruptedException ex) { + System.out.println("Exception " + ex.getMessage()); + } + try { + while (true) { + blockingQueue.take(); + } + } catch (InterruptedException ignored) {} + } + }); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } +} diff --git a/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java b/src/WaitAndNotify_8/Processor.java similarity index 97% rename from JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java rename to src/WaitAndNotify_8/Processor.java index 21171c1..347a274 100644 --- a/JavaMultiThreadingCodes/src/WaitAndNotify_8/Processor.java +++ b/src/WaitAndNotify_8/Processor.java @@ -1,68 +1,68 @@ -package WaitAndNotify_8; - -import java.util.Scanner; - -/** - * 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 {@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 - * - * - * @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 ...."); - wait();//this.wait() is fine. - System.out.println("Resumed."); - } - } - - public void consume() throws InterruptedException { - Scanner scanner = new Scanner(System.in); - Thread.sleep(2000); - synchronized (this) { - System.out.println("Waiting for return key."); - scanner.nextLine(); - System.out.println("Return key pressed."); - notify(); - Thread.sleep(5000); - System.out.println("Consumption done."); - } - } -} +package WaitAndNotify_8; + +import java.util.Scanner; + +/** + * 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 {@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 + * + * + * @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 ...."); + wait();//this.wait() is fine. + System.out.println("Resumed."); + } + } + + public void consume() throws InterruptedException { + Scanner scanner = new Scanner(System.in); + Thread.sleep(2000); + synchronized (this) { + System.out.println("Waiting for return key."); + scanner.nextLine(); + System.out.println("Return key pressed."); + notify(); + Thread.sleep(5000); + System.out.println("Consumption done."); + } + } +} diff --git a/JavaMultiThreadingCodes/src/tests.java b/src/tests.java similarity index 100% rename from JavaMultiThreadingCodes/src/tests.java rename to src/tests.java From 5fbd794c884c4165a1c75baf725d7363c3c677dd Mon Sep 17 00:00:00 2001 From: jsimas Date: Mon, 29 May 2017 17:22:17 +0100 Subject: [PATCH 2/2] Removing old files --- JavaMultiThreadingCodes/build.xml | 73 - JavaMultiThreadingCodes/manifest.mf | 3 - .../nbproject/build-impl.xml | 1413 ----------------- .../nbproject/genfiles.properties | 8 - .../nbproject/project.properties | 73 - JavaMultiThreadingCodes/nbproject/project.xml | 15 - 6 files changed, 1585 deletions(-) delete mode 100644 JavaMultiThreadingCodes/build.xml delete mode 100644 JavaMultiThreadingCodes/manifest.mf delete mode 100644 JavaMultiThreadingCodes/nbproject/build-impl.xml delete mode 100644 JavaMultiThreadingCodes/nbproject/genfiles.properties delete mode 100644 JavaMultiThreadingCodes/nbproject/project.properties delete mode 100644 JavaMultiThreadingCodes/nbproject/project.xml diff --git a/JavaMultiThreadingCodes/build.xml b/JavaMultiThreadingCodes/build.xml deleted file mode 100644 index 5400628..0000000 --- a/JavaMultiThreadingCodes/build.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - - - - - - Builds, tests, and runs the project JavaMultiThreadingCodes. - - - diff --git a/JavaMultiThreadingCodes/manifest.mf b/JavaMultiThreadingCodes/manifest.mf deleted file mode 100644 index 1574df4..0000000 --- a/JavaMultiThreadingCodes/manifest.mf +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -X-COMMENT: Main-Class will be added automatically by build - diff --git a/JavaMultiThreadingCodes/nbproject/build-impl.xml b/JavaMultiThreadingCodes/nbproject/build-impl.xml deleted file mode 100644 index f882b0b..0000000 --- a/JavaMultiThreadingCodes/nbproject/build-impl.xml +++ /dev/null @@ -1,1413 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must set src.dir - Must set test.src.dir - Must set build.dir - Must set dist.dir - Must set build.classes.dir - Must set dist.javadoc.dir - Must set build.test.classes.dir - Must set build.test.results.dir - Must set build.classes.excludes - Must set dist.jar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must set javac.includes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - No tests executed. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must set JVM to use for profiling in profiler.info.jvm - Must set profiler agent JVM arguments in profiler.info.jvmargs.agent - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select some files in the IDE or set javac.includes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - To run this application from the command line without Ant, try: - - java -jar "${dist.jar.resolved}" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select one file in the IDE or set run.class - - - - Must select one file in the IDE or set run.class - - - - - - - - - - - - - - - - - - - - - - - Must select one file in the IDE or set debug.class - - - - - Must select one file in the IDE or set debug.class - - - - - Must set fix.includes - - - - - - - - - - This target only works when run from inside the NetBeans IDE. - - - - - - - - - Must select one file in the IDE or set profile.class - This target only works when run from inside the NetBeans IDE. - - - - - - - - - This target only works when run from inside the NetBeans IDE. - - - - - - - - - - - - - This target only works when run from inside the NetBeans IDE. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select one file in the IDE or set run.class - - - - - - Must select some files in the IDE or set test.includes - - - - - Must select one file in the IDE or set run.class - - - - - Must select one file in the IDE or set applet.url - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select some files in the IDE or set javac.includes - - - - - - - - - - - - - - - - - - - - Some tests failed; see details above. - - - - - - - - - Must select some files in the IDE or set test.includes - - - - Some tests failed; see details above. - - - - Must select some files in the IDE or set test.class - Must select some method in the IDE or set test.method - - - - Some tests failed; see details above. - - - - - Must select one file in the IDE or set test.class - - - - Must select one file in the IDE or set test.class - Must select some method in the IDE or set test.method - - - - - - - - - - - - - - Must select one file in the IDE or set applet.url - - - - - - - - - Must select one file in the IDE or set applet.url - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/JavaMultiThreadingCodes/nbproject/genfiles.properties b/JavaMultiThreadingCodes/nbproject/genfiles.properties deleted file mode 100644 index 9cd2362..0000000 --- a/JavaMultiThreadingCodes/nbproject/genfiles.properties +++ /dev/null @@ -1,8 +0,0 @@ -build.xml.data.CRC32=4d3d93c3 -build.xml.script.CRC32=a6a26692 -build.xml.stylesheet.CRC32=8064a381@1.74.2.48 -# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. -# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. -nbproject/build-impl.xml.data.CRC32=4d3d93c3 -nbproject/build-impl.xml.script.CRC32=fa6ba560 -nbproject/build-impl.xml.stylesheet.CRC32=876e7a8f@1.74.2.48 diff --git a/JavaMultiThreadingCodes/nbproject/project.properties b/JavaMultiThreadingCodes/nbproject/project.properties deleted file mode 100644 index bb953fd..0000000 --- a/JavaMultiThreadingCodes/nbproject/project.properties +++ /dev/null @@ -1,73 +0,0 @@ -annotation.processing.enabled=true -annotation.processing.enabled.in.editor=false -annotation.processing.processor.options= -annotation.processing.processors.list= -annotation.processing.run.all.processors=true -annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output -build.classes.dir=${build.dir}/classes -build.classes.excludes=**/*.java,**/*.form -# This directory is removed when the project is cleaned: -build.dir=build -build.generated.dir=${build.dir}/generated -build.generated.sources.dir=${build.dir}/generated-sources -# Only compile against the classpath explicitly listed here: -build.sysclasspath=ignore -build.test.classes.dir=${build.dir}/test/classes -build.test.results.dir=${build.dir}/test/results -# Uncomment to specify the preferred debugger connection transport: -#debug.transport=dt_socket -debug.classpath=\ - ${run.classpath} -debug.test.classpath=\ - ${run.test.classpath} -# Files in build.classes.dir which should be excluded from distribution jar -dist.archive.excludes= -# This directory is removed when the project is cleaned: -dist.dir=dist -dist.jar=${dist.dir}/JavaMultiThreadingCodes.jar -dist.javadoc.dir=${dist.dir}/javadoc -excludes= -includes=** -jar.compress=false -javac.classpath= -# Space-separated list of extra javac options -javac.compilerargs= -javac.deprecation=false -javac.processorpath=\ - ${javac.classpath} -javac.source=1.7 -javac.target=1.7 -javac.test.classpath=\ - ${javac.classpath}:\ - ${build.classes.dir} -javac.test.processorpath=\ - ${javac.test.classpath} -javadoc.additionalparam= -javadoc.author=false -javadoc.encoding=${source.encoding} -javadoc.noindex=false -javadoc.nonavbar=false -javadoc.notree=false -javadoc.private=false -javadoc.splitindex=true -javadoc.use=true -javadoc.version=false -javadoc.windowtitle= -main.class=javaapplication7.JavaApplication7 -manifest.file=manifest.mf -meta.inf.dir=${src.dir}/META-INF -mkdist.disabled=false -platform.active=default_platform -run.classpath=\ - ${javac.classpath}:\ - ${build.classes.dir} -# Space-separated list of JVM arguments used when running the project. -# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. -# To set system properties for unit tests define test-sys-prop.name=value: -run.jvmargs= -run.test.classpath=\ - ${javac.test.classpath}:\ - ${build.test.classes.dir} -source.encoding=UTF-8 -src.dir=src -test.src.dir=test diff --git a/JavaMultiThreadingCodes/nbproject/project.xml b/JavaMultiThreadingCodes/nbproject/project.xml deleted file mode 100644 index 10729ea..0000000 --- a/JavaMultiThreadingCodes/nbproject/project.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - org.netbeans.modules.java.j2seproject - - - JavaMultiThreadingCodes - - - - - - - - -