Skip to content

Commit ae7cf19

Browse files
committed
Merge pull request Beerkay#2 from IOAyman/master
Code optimized by IOAyman
2 parents 7f40487 + ee43690 commit ae7cf19

File tree

30 files changed

+459
-220
lines changed

30 files changed

+459
-220
lines changed

JavaMultiThreadingCodes/src/CallableAndFuture_13/App.java

Lines changed: 31 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,67 +1,70 @@
11
package CallableAndFuture_13;
22

3+
import java.util.Random;
4+
import java.util.concurrent.*;
5+
36
/**
4-
* Callable and Future in Java to get results from your threads and to allow
7+
* {@link java.util.concurrent.Callable} and
8+
* {@link java.util.concurrent.Future}
9+
* in Java to get results from your threads and to allow
510
* your threads to throw exceptions. Plus, Future allows you to control your
611
* threads, checking to see if they’re running or not, waiting for results and
7-
* even interrupting them or descheduling them.
8-
*
9-
* Runnable is default abstraction for creating a task in Java. It has a single
10-
* method run() that accepts no arguments and returns no value, nor it can throw
12+
* even interrupting them or de-scheduling them.
13+
* <p>
14+
* {@link java.lang.Runnable}
15+
* is the default abstraction for creating a task in Java. It has a single
16+
* method {@link Runnable#run()}
17+
* that accepts no arguments and returns no value, nor it can throw
1118
* any checked exception. To overcome these limitations, Java 5 introduced a new
12-
* task abstraction through Callable interface.
13-
*
14-
* Codes with minor comments are from http://www.caveofprogramming.com/youtube/
19+
* task abstraction through {@link java.util.concurrent.Callable} interface.
20+
* <br><br>
21+
* Codes with minor comments are from
22+
* <a href="http://www.caveofprogramming.com/youtube/">
23+
* <em>http://www.caveofprogramming.com/youtube/</em>
24+
* </a>
25+
* <br>
1526
* also freely available at
16-
* https://www.udemy.com/java-multithreading/?couponCode=FREE
27+
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
28+
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
29+
* </a>
1730
*
1831
* @author Z.B. Celik <[email protected]>
1932
*/
20-
import java.io.IOException;
21-
import java.util.Random;
22-
import java.util.concurrent.Callable;
23-
import java.util.concurrent.ExecutionException;
24-
import java.util.concurrent.ExecutorService;
25-
import java.util.concurrent.Executors;
26-
import java.util.concurrent.Future;
27-
import java.util.concurrent.TimeUnit;
28-
2933
public class App {
3034

3135
public static void main(String[] args) throws InterruptedException {
3236
ExecutorService executor = Executors.newCachedThreadPool();
37+
3338
//anonymous call of Callable
3439
Future<Integer> future = executor.submit(new Callable<Integer>() {
3540

3641
@Override
3742
//return value is Integer
38-
public Integer call() throws Exception {
43+
public Integer call() throws TimeoutException {
3944
Random random = new Random();
4045
int duration = random.nextInt(4000);
4146
if (duration > 2000) {
42-
throw new IOException("Sleeping for too long.");
47+
throw new TimeoutException ("Sleeping for too long.");
4348
}
44-
System.out.println("Starting ...");
4549

50+
System.out.println("Starting ...");
4651
try {
4752
Thread.sleep(duration);
48-
} catch (InterruptedException e) {
49-
e.printStackTrace();
50-
}
53+
} catch (InterruptedException ignored) {}
5154
System.out.println("Finished.");
5255
return duration;
5356
}
5457
});
5558

5659
executor.shutdown();
57-
executor.awaitTermination(1, TimeUnit.DAYS);
60+
// executor.awaitTermination(1, TimeUnit.DAYS);
5861
try {
5962
//get returned value from call()
6063
System.out.println("Result is: " + future.get());
61-
} catch (InterruptedException e) {
62-
e.printStackTrace();
64+
65+
} catch (InterruptedException ignored) {
6366
} catch (ExecutionException e) {
64-
IOException ex = (IOException) e.getCause();
67+
TimeoutException ex = (TimeoutException) e.getCause();
6568
System.out.println(ex.getMessage());
6669
}
6770
}

JavaMultiThreadingCodes/src/CallableAndFuture_13/App2.java

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,18 @@
11
package CallableAndFuture_13;
22

3+
import java.util.ArrayList;
4+
import java.util.concurrent.*;
5+
36
/**
47
* Understanding Callable
58
*
69
* @author Z.B. Celik <[email protected]>
710
*/
8-
import java.util.ArrayList;
9-
import java.util.concurrent.Callable;
10-
import java.util.concurrent.ExecutionException;
11-
import java.util.concurrent.ExecutorService;
12-
import java.util.concurrent.Executors;
13-
import java.util.concurrent.Future;
14-
import java.util.concurrent.TimeUnit;
15-
1611
class MyCallable implements Callable<Integer> {
1712

18-
Integer value;
13+
int value;
1914

20-
public MyCallable(Integer i) {
15+
public MyCallable(int i) {
2116
this.value = i;
2217
}
2318

@@ -38,8 +33,8 @@ public class App2 {
3833
public static void main(String[] args) throws InterruptedException {
3934
ArrayList<Integer> list = new ArrayList<>();
4035
ExecutorService executor = Executors.newCachedThreadPool();
41-
Future<Integer> future = null;
42-
Callable<Integer> callable = null;
36+
Future<Integer> future;
37+
4338
for (int i = 1; i < 10; i++) {
4439
future = executor.submit(new MyCallable(i));
4540
try {
@@ -50,7 +45,9 @@ public static void main(String[] args) throws InterruptedException {
5045
}
5146

5247
executor.shutdown();
48+
//this is ont necessary in this case .. but .. good practice :)
5349
executor.awaitTermination(1, TimeUnit.DAYS);
50+
5451
for (int i = 0; i < list.size(); i++) {
5552
//get returned values from call()
5653
System.out.println("List Values " + i + " Value: " + list.get(i));
Lines changed: 40 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,47 @@
11
package CallableAndFuture_13;
22

3-
import java.util.concurrent.Callable;
4-
import java.util.concurrent.ExecutorService;
5-
import java.util.concurrent.Future;
6-
import java.util.concurrent.ScheduledThreadPoolExecutor;
3+
import java.util.concurrent.*;
74

85
/**
9-
* Source:http://java-x.blogspot.com.tr/2006/11/java-5-concurrency-callable-and-future.html
10-
* Till Java 1.4, threads could be implemented by either implementing Runnable
11-
* or extending Thread. This was quite simple, but had a serious limitation -
6+
* Source:
7+
* <a href="http://java-x.blogspot.com.tr/2006/11/java-5-concurrency-callable-and-future.html">
8+
* http://java-x.blogspot.com.tr/2006/11/java-5-concurrency-callable-and-future.html
9+
* </a>
10+
* <p>
11+
* Till Java 1.4, threads could be implemented by either implementing
12+
* {@link java.lang.Runnable} or extending {@link java.lang.Thread}.
13+
* This was quite simple, but had a serious limitation;
1214
* They have a run method that cannot return values. In order to side-step this,
1315
* most programmers use side-effects (writing to a file etc.) to mimic returning
14-
* values to the invoker of the thread. Java 5 introduces the Callable
15-
* interface, that allows users to return values from a thread
16-
*
17-
* Runnable vs Callable<T>
18-
* Runnable Introduced in Java 1.0 Callable<T> Introduced in Java 1.5 as part of
19-
* java.util.concurrent library
20-
*
21-
* Runnable cannot be parametrized Callable is a parametrized type whose type
22-
* parameter indicates the return type of its run method Classes implementing
23-
*
16+
* values to the invoker of the thread. Java 5 introduces the
17+
* {@link java.util.concurrent.Callable} interface, that allows users to
18+
* return values from a thread.
19+
* </p>
20+
* <p>
21+
* {@link java.lang.Runnable} vs {@link java.util.concurrent.Callable} :
22+
* <ul>
23+
* <li>
24+
* Runnable Introduced in Java 1.0. Callable<T> Introduced in Java 1.5 as
25+
* part of
26+
* {@link java.util.concurrent} library.
27+
* </li>
28+
* <li>
29+
* Runnable cannot be parametrized .Callable is a parametrized type whose type
30+
* parameter indicates the return type of its run method Classes implementing.
31+
* </li>
32+
* <li>
2433
* Runnable needs to implement run() method, classes implementing Callable needs
25-
* to implement call() method
26-
*
27-
* Runnable.run() returns no value, Callable.call() returns a value of Type T
28-
*
34+
* to implement call() method.
35+
* </li>
36+
* <li>
37+
* Runnable.run() returns no value, Callable.call() returns a value of Type T.
38+
* </li>
39+
* <li>
2940
* Runnable can not throw checked exceptions, Callable can throw checked
30-
* exceptions
41+
* exceptions.
42+
* </li>
43+
* </ul>
44+
* </p>
3145
*
3246
* @author Z.B. Celik <[email protected]>
3347
*/
@@ -58,20 +72,17 @@ public void setMyName(int myName) {
5872

5973
public class CallableTester {
6074

61-
public static void main(String[] args) {
75+
public static void main(String[] args) throws InterruptedException {
6276

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

6781
try {
6882
System.out.println("Future value: " + future.get());
69-
} catch (Exception e) {
70-
e.printStackTrace();
71-
} finally {
72-
executor.shutdown();
73-
executor.isTerminated();
74-
}
83+
} catch (Exception ignored) {}
84+
executor.shutdown();
85+
executor.awaitTermination(1, TimeUnit.HOURS);
7586
}
7687

7788
}

JavaMultiThreadingCodes/src/Deadlock_11/Account.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
package Deadlock_11;
22

33
/**
4-
* Codes with minor comments are from http://www.caveofprogramming.com/youtube/
4+
* Codes with minor comments are from
5+
* <a href="http://www.caveofprogramming.com/youtube/">
6+
* <em>http://www.caveofprogramming.com/youtube/</em>
7+
* </a>
8+
* <br>
59
* also freely available at
6-
* https://www.udemy.com/java-multithreading/?couponCode=FREE
10+
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
11+
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
12+
* </a>
713
*
814
* @author Z.B. Celik <[email protected]>
915
*/
Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
11
package Deadlock_11;
22

33
/**
4-
* Deadlock can occur in a situation when a thread is waiting for an object
5-
* lock, that is acquired by another thread and second thread is waiting for an
4+
* <a href="https://wikipedia.org/wiki/Deadlock">Deadlock</a>
5+
* can occur in a situation when a thread is waiting for an object's lock,
6+
* that is acquired by another thread and the second thread is waiting for an
67
* object lock that is acquired by first thread. Since, both threads are waiting
78
* for each other to release the lock, the condition is called deadlock. If you
89
* make sure that all locks are always taken in the same order by any thread,
910
* deadlocks cannot occur.
10-
*
11-
* Codes with minor comments are from http://www.caveofprogramming.com/youtube/
11+
* <br><br>
12+
* Codes with minor comments are from
13+
* <a href="http://www.caveofprogramming.com/youtube/">
14+
* <em>http://www.caveofprogramming.com/youtube/</em>
15+
* </a>
16+
* <br>
1217
* also freely available at
13-
* https://www.udemy.com/java-multithreading/?couponCode=FREE
18+
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
19+
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
20+
* </a>
1421
*
1522
* @author Z.B. Celik <[email protected]>
1623
*/
@@ -22,21 +29,15 @@ public static void main(String[] args) throws Exception {
2229
public void run() {
2330
try {
2431
runner.firstThread();
25-
} catch (InterruptedException e) {
26-
// TODO Auto-generated catch block
27-
e.printStackTrace();
28-
}
32+
} catch (InterruptedException ignored) {}
2933
}
3034
});
3135

3236
Thread t2 = new Thread(new Runnable() {
3337
public void run() {
3438
try {
3539
runner.secondThread();
36-
} catch (InterruptedException e) {
37-
// TODO Auto-generated catch block
38-
e.printStackTrace();
39-
}
40+
} catch (InterruptedException ignored) {}
4041
}
4142
});
4243

@@ -46,5 +47,4 @@ public void run() {
4647
t2.join();
4748
runner.finished();
4849
}
49-
5050
}

JavaMultiThreadingCodes/src/Deadlock_11/Runner.java

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,25 @@
1-
package Deadlock_11;
1+
package Deadlock_11;
2+
3+
import java.util.Random;
4+
import java.util.concurrent.locks.Lock;
5+
import java.util.concurrent.locks.ReentrantLock;
26

37
/**
4-
* Deadlocks
5-
*
6-
* Codes with minor comments are from http://www.caveofprogramming.com/youtube/
8+
* <a href="https://wikipedia.org/wiki/Deadlock">Deadlock</a>
9+
* <br><br>
10+
* Codes with minor comments are from
11+
* <a href="http://www.caveofprogramming.com/youtube/">
12+
* <em>http://www.caveofprogramming.com/youtube/</em>
13+
* </a>
14+
* <br>
715
* also freely available at
8-
* https://www.udemy.com/java-multithreading/?couponCode=FREE
16+
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
17+
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
18+
* </a>
919
*
1020
* @author Z.B. Celik <[email protected]>
1121
*/
12-
import java.util.Random;
13-
import java.util.concurrent.locks.Lock;
14-
import java.util.concurrent.locks.ReentrantLock;
15-
22+
@SuppressWarnings("InfiniteLoopStatement")
1623
public class Runner {
1724

1825
private Account acc1 = new Account();
@@ -38,15 +45,9 @@ private void acquireLocks(Lock firstLock, Lock secondLock) throws InterruptedExc
3845
gotFirstLock = firstLock.tryLock();
3946
gotSecondLock = secondLock.tryLock();
4047
} finally {
41-
if (gotFirstLock && gotSecondLock) {
42-
return;
43-
}
44-
if (gotFirstLock) {
45-
firstLock.unlock();
46-
}
47-
if (gotSecondLock) {
48-
secondLock.unlock();
49-
}
48+
if (gotFirstLock && gotSecondLock) return;
49+
else if (gotFirstLock) firstLock.unlock();
50+
else if (gotSecondLock) secondLock.unlock();
5051
}
5152
// Locks not acquired
5253
Thread.sleep(1);

0 commit comments

Comments
 (0)