Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 31 additions & 28 deletions JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java
Original file line number Diff line number Diff line change
@@ -1,67 +1,70 @@
package CallableAndFuture_13;

import java.util.Random;
import java.util.concurrent.*;

/**
* Callable and Future in Java to get results from your threads and to allow
* {@link java.util.concurrent.Callable} and
* {@link java.util.concurrent.Future}
* in Java to get results from your threads and to allow
* your threads to throw exceptions. Plus, Future allows you to control your
* threads, checking to see if they’re running or not, waiting for results and
* even interrupting them or descheduling them.
*
* Runnable is default abstraction for creating a task in Java. It has a single
* method run() that accepts no arguments and returns no value, nor it can throw
* even interrupting them or de-scheduling them.
* <p>
* {@link java.lang.Runnable}
* is the default abstraction for creating a task in Java. It has a single
* method {@link Runnable#run()}
* that accepts no arguments and returns no value, nor it can throw
* any checked exception. To overcome these limitations, Java 5 introduced a new
* task abstraction through Callable interface.
*
* Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* task abstraction through {@link java.util.concurrent.Callable} interface.
* <br><br>
* Codes with minor comments are from
* <a href="http://www.caveofprogramming.com/youtube/">
* <em>http://www.caveofprogramming.com/youtube/</em>
* </a>
* <br>
* also freely available at
* https://www.udemy.com/java-multithreading/?couponCode=FREE
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
* </a>
*
* @author Z.B. Celik <celik.berkay@gmail.com>
*/
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class App {

public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();

//anonymous call of Callable
Future<Integer> future = executor.submit(new Callable<Integer>() {

@Override
//return value is Integer
public Integer call() throws Exception {
public Integer call() throws TimeoutException {
Random random = new Random();
int duration = random.nextInt(4000);
if (duration > 2000) {
throw new IOException("Sleeping for too long.");
throw new TimeoutException ("Sleeping for too long.");
}
System.out.println("Starting ...");

System.out.println("Starting ...");
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (InterruptedException ignored) {}
System.out.println("Finished.");
return duration;
}
});

executor.shutdown();
executor.awaitTermination(1, TimeUnit.DAYS);
// executor.awaitTermination(1, TimeUnit.DAYS);
try {
//get returned value from call()
System.out.println("Result is: " + future.get());
} catch (InterruptedException e) {
e.printStackTrace();

} catch (InterruptedException ignored) {
} catch (ExecutionException e) {
IOException ex = (IOException) e.getCause();
TimeoutException ex = (TimeoutException) e.getCause();
System.out.println(ex.getMessage());
}
}
Expand Down
21 changes: 9 additions & 12 deletions JavaMultiThreadingCodes/src/CallableAndFuture_13/App2.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
package CallableAndFuture_13;

import java.util.ArrayList;
import java.util.concurrent.*;

/**
* Understanding Callable
*
* @author Z.B. Celik <celik.berkay@gmail.com>
*/
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

class MyCallable implements Callable<Integer> {

Integer value;
int value;

public MyCallable(Integer i) {
public MyCallable(int i) {
this.value = i;
}

Expand All @@ -38,8 +33,8 @@ public class App2 {
public static void main(String[] args) throws InterruptedException {
ArrayList<Integer> list = new ArrayList<>();
ExecutorService executor = Executors.newCachedThreadPool();
Future<Integer> future = null;
Callable<Integer> callable = null;
Future<Integer> future;

for (int i = 1; i < 10; i++) {
future = executor.submit(new MyCallable(i));
try {
Expand All @@ -50,7 +45,9 @@ public static void main(String[] args) throws InterruptedException {
}

executor.shutdown();
//this is ont necessary in this case .. but .. good practice :)
executor.awaitTermination(1, TimeUnit.DAYS);

for (int i = 0; i < list.size(); i++) {
//get returned values from call()
System.out.println("List Values " + i + " Value: " + list.get(i));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,33 +1,47 @@
package CallableAndFuture_13;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.*;

/**
* Source:http://java-x.blogspot.com.tr/2006/11/java-5-concurrency-callable-and-future.html
* Till Java 1.4, threads could be implemented by either implementing Runnable
* or extending Thread. This was quite simple, but had a serious limitation -
* Source:
* <a href="http://java-x.blogspot.com.tr/2006/11/java-5-concurrency-callable-and-future.html">
* http://java-x.blogspot.com.tr/2006/11/java-5-concurrency-callable-and-future.html
* </a>
* <p>
* Till Java 1.4, threads could be implemented by either implementing
* {@link java.lang.Runnable} or extending {@link java.lang.Thread}.
* This was quite simple, but had a serious limitation;
* They have a run method that cannot return values. In order to side-step this,
* most programmers use side-effects (writing to a file etc.) to mimic returning
* values to the invoker of the thread. Java 5 introduces the Callable
* interface, that allows users to return values from a thread
*
* Runnable vs Callable<T>
* Runnable Introduced in Java 1.0 Callable<T> Introduced in Java 1.5 as part of
* java.util.concurrent library
*
* Runnable cannot be parametrized Callable is a parametrized type whose type
* parameter indicates the return type of its run method Classes implementing
*
* values to the invoker of the thread. Java 5 introduces the
* {@link java.util.concurrent.Callable} interface, that allows users to
* return values from a thread.
* </p>
* <p>
* {@link java.lang.Runnable} vs {@link java.util.concurrent.Callable} :
* <ul>
* <li>
* Runnable Introduced in Java 1.0. Callable<T> Introduced in Java 1.5 as
* part of
* {@link java.util.concurrent} library.
* </li>
* <li>
* Runnable cannot be parametrized .Callable is a parametrized type whose type
* parameter indicates the return type of its run method Classes implementing.
* </li>
* <li>
* Runnable needs to implement run() method, classes implementing Callable needs
* to implement call() method
*
* Runnable.run() returns no value, Callable.call() returns a value of Type T
*
* to implement call() method.
* </li>
* <li>
* Runnable.run() returns no value, Callable.call() returns a value of Type T.
* </li>
* <li>
* Runnable can not throw checked exceptions, Callable can throw checked
* exceptions
* exceptions.
* </li>
* </ul>
* </p>
*
* @author Z.B. Celik <celik.berkay@gmail.com>
*/
Expand Down Expand Up @@ -58,20 +72,17 @@ public void setMyName(int myName) {

public class CallableTester {

public static void main(String[] args) {
public static void main(String[] args) throws InterruptedException {

Callable<Integer> callable = new CallableImpl(2);
ExecutorService executor = new ScheduledThreadPoolExecutor(1);
Future<Integer> future = executor.submit(callable);

try {
System.out.println("Future value: " + future.get());
} catch (Exception e) {
e.printStackTrace();
} finally {
executor.shutdown();
executor.isTerminated();
}
} catch (Exception ignored) {}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.HOURS);
}

}
10 changes: 8 additions & 2 deletions JavaMultiThreadingCodes/src/Deadlock_11/Account.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
package Deadlock_11;

/**
* Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* Codes with minor comments are from
* <a href="http://www.caveofprogramming.com/youtube/">
* <em>http://www.caveofprogramming.com/youtube/</em>
* </a>
* <br>
* also freely available at
* https://www.udemy.com/java-multithreading/?couponCode=FREE
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
* </a>
*
* @author Z.B. Celik <celik.berkay@gmail.com>
*/
Expand Down
28 changes: 14 additions & 14 deletions JavaMultiThreadingCodes/src/Deadlock_11/App.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
package Deadlock_11;

/**
* Deadlock can occur in a situation when a thread is waiting for an object
* lock, that is acquired by another thread and second thread is waiting for an
* <a href="https://wikipedia.org/wiki/Deadlock">Deadlock</a>
* can occur in a situation when a thread is waiting for an object's lock,
* that is acquired by another thread and the second thread is waiting for an
* object lock that is acquired by first thread. Since, both threads are waiting
* for each other to release the lock, the condition is called deadlock. If you
* make sure that all locks are always taken in the same order by any thread,
* deadlocks cannot occur.
*
* Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* <br><br>
* Codes with minor comments are from
* <a href="http://www.caveofprogramming.com/youtube/">
* <em>http://www.caveofprogramming.com/youtube/</em>
* </a>
* <br>
* also freely available at
* https://www.udemy.com/java-multithreading/?couponCode=FREE
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
* </a>
*
* @author Z.B. Celik <celik.berkay@gmail.com>
*/
Expand All @@ -22,21 +29,15 @@ public static void main(String[] args) throws Exception {
public void run() {
try {
runner.firstThread();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InterruptedException ignored) {}
}
});

Thread t2 = new Thread(new Runnable() {
public void run() {
try {
runner.secondThread();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InterruptedException ignored) {}
}
});

Expand All @@ -46,5 +47,4 @@ public void run() {
t2.join();
runner.finished();
}

}
37 changes: 19 additions & 18 deletions JavaMultiThreadingCodes/src/Deadlock_11/Runner.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
package Deadlock_11;
package Deadlock_11;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
* Deadlocks
*
* Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* <a href="https://wikipedia.org/wiki/Deadlock">Deadlock</a>
* <br><br>
* Codes with minor comments are from
* <a href="http://www.caveofprogramming.com/youtube/">
* <em>http://www.caveofprogramming.com/youtube/</em>
* </a>
* <br>
* also freely available at
* https://www.udemy.com/java-multithreading/?couponCode=FREE
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
* </a>
*
* @author Z.B. Celik <celik.berkay@gmail.com>
*/
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@SuppressWarnings("InfiniteLoopStatement")
public class Runner {

private Account acc1 = new Account();
Expand All @@ -38,15 +45,9 @@ private void acquireLocks(Lock firstLock, Lock secondLock) throws InterruptedExc
gotFirstLock = firstLock.tryLock();
gotSecondLock = secondLock.tryLock();
} finally {
if (gotFirstLock && gotSecondLock) {
return;
}
if (gotFirstLock) {
firstLock.unlock();
}
if (gotSecondLock) {
secondLock.unlock();
}
if (gotFirstLock && gotSecondLock) return;
else if (gotFirstLock) firstLock.unlock();
else if (gotSecondLock) secondLock.unlock();
}
// Locks not acquired
Thread.sleep(1);
Expand Down
Loading