Skip to content

Commit d9c1a5c

Browse files
committed
java concurrency examples
1 parent 078ea56 commit d9c1a5c

9 files changed

Lines changed: 363 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<parent>
6+
<artifactId>tryout-java-concurrency</artifactId>
7+
<groupId>com.fd</groupId>
8+
<version>1.0-SNAPSHOT</version>
9+
</parent>
10+
<modelVersion>4.0.0</modelVersion>
11+
12+
<artifactId>java-concurrency</artifactId>
13+
14+
<build>
15+
<plugins>
16+
<plugin>
17+
<groupId>org.apache.maven.plugins</groupId>
18+
<artifactId>maven-compiler-plugin</artifactId>
19+
<configuration>
20+
<source>8</source>
21+
<target>8</target>
22+
</configuration>
23+
</plugin>
24+
</plugins>
25+
</build>
26+
27+
28+
</project>
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package com.fd.tryout.concurrency.java;
2+
3+
import java.util.List;
4+
import java.util.concurrent.CountDownLatch;
5+
import java.util.concurrent.ExecutorService;
6+
import java.util.concurrent.Executors;
7+
import java.util.stream.Collectors;
8+
import java.util.stream.Stream;
9+
10+
/**
11+
* This is a very nice example of using CountDownLatch. In this code we generate 15 threads, start them but
12+
* block them all until all the threads get into their run method. Fire the begin sign, and wait until
13+
* all the workers finish their job.
14+
*
15+
* @author fdanismaz
16+
* date: 11/24/18 11:18 PM
17+
*/
18+
public class PoolOfThreadsWaitingToBegin {
19+
20+
private static class Worker implements Runnable {
21+
22+
private int id;
23+
private CountDownLatch readyThreadCounter;
24+
private CountDownLatch launcherBlocker;
25+
private CountDownLatch completedThreadCounter;
26+
27+
28+
public Worker(int id, CountDownLatch readyThreadCounter,
29+
CountDownLatch launcherBlocker, CountDownLatch completedThreadCounter) {
30+
this.id = id;
31+
this.readyThreadCounter = readyThreadCounter;
32+
this.launcherBlocker = launcherBlocker;
33+
this.completedThreadCounter = completedThreadCounter;
34+
}
35+
36+
@Override
37+
public void run() {
38+
// Thread is ready. Countdown
39+
System.out.println(String.format("Worker %d is ready", this.id));
40+
this.readyThreadCounter.countDown();
41+
42+
// Wait for other threads to be ready
43+
try {
44+
this.launcherBlocker.await();
45+
} catch (InterruptedException e) {
46+
e.printStackTrace();
47+
}
48+
49+
// do work
50+
System.out.println(String.format("Running job %d", this.id));
51+
try {
52+
Thread.sleep(1000);
53+
} catch (InterruptedException e) {
54+
e.printStackTrace();
55+
}
56+
57+
// Thread has completed its job, countdown
58+
this.completedThreadCounter.countDown();
59+
}
60+
}
61+
62+
private static CountDownLatch readyThreadCounter = new CountDownLatch(15);
63+
private static CountDownLatch launcherBlocker = new CountDownLatch(1);
64+
private static CountDownLatch completedThreadCounter = new CountDownLatch(15);
65+
66+
public static int id = 1;
67+
68+
public static void main(String[] args) throws InterruptedException {
69+
ExecutorService s = Executors.newCachedThreadPool();
70+
System.out.println("Genearting threads...");
71+
List<? extends Runnable> workerList = Stream
72+
.generate(() -> new Worker(id++, readyThreadCounter, launcherBlocker, completedThreadCounter))
73+
.limit(15)
74+
.collect(Collectors.toList());
75+
76+
System.out.println("Threads are generated, waiting for them to become ready...");
77+
workerList.forEach(worker -> s.submit(worker));
78+
readyThreadCounter.await(); // Wait until all threads get in their run method
79+
System.out.println("All threads are ready");
80+
81+
// all threads are waiting for the begin sign, so let's start the threads
82+
Thread.sleep(5000);
83+
System.out.println("Firing the begin sign...");
84+
launcherBlocker.countDown();
85+
86+
completedThreadCounter.await();
87+
// all threads have completed their work
88+
System.out.println("All the workers completed their jobs");
89+
90+
s.shutdown();
91+
92+
}
93+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.fd.tryout.concurrency.java;
2+
3+
/**
4+
* @author fdanismaz
5+
* date: 11/25/18 4:36 PM
6+
*/
7+
public class TryDaemonThread {
8+
9+
public static void main(String[] args) {
10+
Thread t = new Thread(() -> {
11+
try {
12+
Thread.sleep(100);
13+
} catch (InterruptedException e) {
14+
e.printStackTrace();
15+
}
16+
System.out.println("A Daemon thread!");
17+
});
18+
19+
t.setDaemon(true);
20+
t.start();
21+
22+
System.out.println("Program finished...");
23+
}
24+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.fd.tryout.concurrency.java;
2+
3+
import java.util.concurrent.Executor;
4+
5+
/**
6+
* Executor is an interface that represents an object that executes provided tasks.
7+
*
8+
* It depends on the particular implementation if the task should be run on a new or current thread
9+
*
10+
* @author fdanismaz
11+
* date: 11/24/18 9:58 AM
12+
*/
13+
public class TryExecutor {
14+
public static void main(String[] args) {
15+
Executor e = command -> command.run();
16+
e.execute(() -> System.out.println("Hello World!"));
17+
System.out.println("Program finished...");
18+
}
19+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.fd.tryout.concurrency.java;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
6+
/**
7+
* ExecutorService is a complete solution for asynchronous processing. It manages an in-memory queue and
8+
* schedules submitted tasks based on thread availability.
9+
*
10+
* shutdown() - waits till all submitted tasks are finished
11+
* shutdownNow() - immediately terminates all the pending/executing tasks
12+
*
13+
* @author fdanismaz
14+
* date: 11/24/18 9:57 AM
15+
*/
16+
public class TryExecutorService {
17+
18+
public static void main(String[] args) {
19+
20+
ExecutorService s = Executors.newFixedThreadPool(5);
21+
Runnable r = () -> System.out.println("Hello world!");
22+
s.submit(r);
23+
s.submit(r);
24+
s.submit(r);
25+
s.submit(r);
26+
s.submit(r);
27+
s.submit(r);
28+
s.submit(r);
29+
s.submit(r);
30+
s.submit(r);
31+
s.submit(r);
32+
s.submit(r);
33+
s.submit(r);
34+
s.submit(r);
35+
s.submit(r);
36+
s.submit(r);
37+
System.out.println("Program finished...");
38+
s.shutdown();
39+
}
40+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.fd.tryout.concurrency.java;
2+
3+
import java.util.concurrent.*;
4+
5+
/**
6+
* @author fdanismaz
7+
* date: 11/24/18 10:05 PM
8+
*/
9+
public class TryFuture {
10+
11+
public static void main(String[] args) throws InterruptedException {
12+
ScheduledExecutorService s = Executors.newScheduledThreadPool(5);
13+
14+
// Start after 3 seconds, wait for 10 seconds and return John Doe
15+
Future<String> asyncResult = s.schedule(() -> {
16+
Thread.sleep(10000);
17+
return "Jonh Doe";
18+
}, 3, TimeUnit.SECONDS);
19+
20+
// Wait for the job to be completed
21+
while (!asyncResult.isDone() && !asyncResult.isCancelled()) {
22+
System.out.println("Waiting for the job to be completed...");
23+
Thread.sleep(1000);
24+
}
25+
26+
try {
27+
System.out.println(asyncResult.get());
28+
} catch (Exception e) {
29+
e.printStackTrace();
30+
}
31+
32+
s.shutdown();
33+
34+
}
35+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.fd.tryout.concurrency.java;
2+
3+
import java.util.concurrent.Executors;
4+
import java.util.concurrent.ScheduledExecutorService;
5+
import java.util.concurrent.TimeUnit;
6+
7+
/**
8+
* ScheduledExecutorService is similar to executor service, but it can perform tasks periodically
9+
*
10+
* @author fdanismaz
11+
* date: 11/24/18 2:07 PM
12+
*/
13+
public class TryScheduledExecutorService {
14+
15+
public static void main(String[] args) throws InterruptedException {
16+
ScheduledExecutorService s = Executors.newScheduledThreadPool(10);
17+
s.schedule(() -> System.out.println("Hello World!"), 1, TimeUnit.SECONDS);
18+
19+
//s.shutdown(); // We cannot use the executor service after it is shutdown
20+
21+
s.scheduleAtFixedRate(() -> System.out.println("Hello World 2"), 3, 1, TimeUnit.SECONDS);
22+
23+
Thread.sleep(10000);
24+
s.shutdown();
25+
System.out.println("Program Finished");
26+
}
27+
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package com.fd.tryout.concurrency.java;
2+
3+
import java.time.Duration;
4+
import java.time.LocalDateTime;
5+
import java.util.List;
6+
import java.util.concurrent.CountDownLatch;
7+
import java.util.concurrent.ExecutorService;
8+
import java.util.concurrent.Executors;
9+
import java.util.concurrent.Semaphore;
10+
import java.util.stream.Collectors;
11+
import java.util.stream.Stream;
12+
13+
/**
14+
* @author fdanismaz
15+
* date: 11/25/18 12:31 PM
16+
*/
17+
public class TrySemaphore {
18+
19+
private static class Worker implements Runnable {
20+
21+
private Semaphore semaphore;
22+
private int id;
23+
private CountDownLatch completedThreadCountdown;
24+
25+
public Worker(int id, Semaphore semaphore, CountDownLatch completedThreadCountdown) {
26+
this.id = id;
27+
this.semaphore = semaphore;
28+
this.completedThreadCountdown = completedThreadCountdown;
29+
}
30+
31+
@Override
32+
public void run() {
33+
System.out.println(String.format("Thread %d is ready. Waiting for permit.", this.id));
34+
//if (this.semaphore.tryAcquire()) {
35+
try {
36+
this.semaphore.acquire();
37+
System.out.println(String.format("Thread %d starting its job. Permit count: %d...", this.id, this.semaphore.availablePermits()));
38+
39+
// do the job
40+
//Thread.sleep(2000);
41+
42+
synchronized (this.semaphore) {
43+
this.semaphore.release();
44+
System.out.println(String.format("Thread %d finished. Permit count: %d ", this.id, this.semaphore.availablePermits()));
45+
this.completedThreadCountdown.countDown();
46+
}
47+
48+
} catch (InterruptedException e) {
49+
e.printStackTrace();
50+
}
51+
//}
52+
}
53+
}
54+
55+
private static int id = 1;
56+
57+
public static void main(String[] args) throws InterruptedException {
58+
int threadCount = 1000;
59+
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
60+
Semaphore semaphore = new Semaphore(5, true);
61+
CountDownLatch completedThreadCountdown = new CountDownLatch(threadCount);
62+
63+
// Create threads
64+
List<? extends Runnable> workers = Stream
65+
.generate(() -> new Worker(id++, semaphore, completedThreadCountdown))
66+
.limit(threadCount)
67+
.collect(Collectors.toList());
68+
69+
LocalDateTime startTime = LocalDateTime.now();
70+
71+
// Start threads
72+
workers.forEach(w -> executorService.submit(w));
73+
74+
completedThreadCountdown.await();
75+
76+
LocalDateTime endTime = LocalDateTime.now();
77+
78+
executorService.shutdown();
79+
System.out.println(String.format("Total work time: %s milliseconds", Duration.between(startTime, endTime).getNano() / 1000 / 1000));
80+
}
81+
}

‎concurrency/pom.xml‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>com.fd</groupId>
8+
<artifactId>tryout-java-concurrency</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
<modules>
11+
<module>java-concurrency</module>
12+
</modules>
13+
<packaging>pom</packaging>
14+
15+
16+
</project>

0 commit comments

Comments
 (0)