Skip to content

Commit d76aa38

Browse files
committed
Merge remote-tracking branch 'eugenp/master'
2 parents 8fa09b2 + a02e758 commit d76aa38

23 files changed

Lines changed: 1276 additions & 533 deletions

File tree

‎guest/thread-pools/pom.xml‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>com.stackify</groupId>
5+
<artifactId>thread-pools</artifactId>
6+
<version>0.0.1-SNAPSHOT</version>
7+
8+
<dependencies>
9+
<dependency>
10+
<groupId>ch.qos.logback</groupId>
11+
<artifactId>logback-classic</artifactId>
12+
<version>1.2.3</version>
13+
</dependency>
14+
</dependencies>
15+
16+
<build>
17+
<plugins>
18+
<plugin>
19+
<artifactId>maven-compiler-plugin</artifactId>
20+
<version>3.5.1</version>
21+
<configuration>
22+
<source>1.8</source>
23+
<target>1.8</target>
24+
</configuration>
25+
</plugin>
26+
</plugins>
27+
</build>
28+
</project>
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.stackify.models;
2+
3+
public class Employee {
4+
private String name;
5+
private double salary;
6+
7+
public String getName() {
8+
return name;
9+
}
10+
11+
public void setName(String name) {
12+
this.name = name;
13+
}
14+
15+
public double getSalary() {
16+
return salary;
17+
}
18+
19+
public void setSalary(double salary) {
20+
this.salary = salary;
21+
}
22+
23+
public Employee(String name, double salary) {
24+
super();
25+
this.name = name;
26+
this.salary = salary;
27+
}
28+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.stackify.services;
2+
3+
import com.stackify.models.Employee;
4+
5+
public class EmployeeService {
6+
public double calculateBonus(Employee employee) {
7+
return 0.1 * employee.getSalary();
8+
}
9+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.stackify.threadpools;
2+
3+
import java.math.BigInteger;
4+
import java.util.ArrayList;
5+
import java.util.Collection;
6+
import java.util.List;
7+
import java.util.concurrent.ForkJoinTask;
8+
import java.util.concurrent.RecursiveTask;
9+
import java.util.stream.IntStream;
10+
11+
import org.slf4j.Logger;
12+
import org.slf4j.LoggerFactory;
13+
14+
public class FactorialTask extends RecursiveTask<BigInteger> {
15+
16+
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
17+
18+
private static final long serialVersionUID = 1L;
19+
20+
private int start = 1;
21+
private int n;
22+
23+
private static final int THRESHOLD = 20;
24+
25+
public FactorialTask(int n) {
26+
this.n = n;
27+
}
28+
29+
public FactorialTask(int start, int n) {
30+
logger.info("New FactorialTask Created");
31+
this.start = start;
32+
this.n = n;
33+
}
34+
35+
@Override
36+
protected BigInteger compute() {
37+
if ((n - start) >= THRESHOLD) {
38+
return ForkJoinTask.invokeAll(createSubtasks())
39+
.stream()
40+
.map(ForkJoinTask::join)
41+
.reduce(BigInteger.ONE, BigInteger::multiply);
42+
} else {
43+
return calculate(start, n);
44+
}
45+
}
46+
47+
private Collection<FactorialTask> createSubtasks() {
48+
List<FactorialTask> dividedTasks = new ArrayList<>();
49+
50+
int mid = (start + n) / 2;
51+
52+
dividedTasks.add(new FactorialTask(start, mid));
53+
dividedTasks.add(new FactorialTask(mid + 1, n));
54+
return dividedTasks;
55+
}
56+
57+
private BigInteger calculate(int start, int n) {
58+
logger.info("Calculate factorial from " + start + " to " + n);
59+
return IntStream.rangeClosed(start, n)
60+
.mapToObj(BigInteger::valueOf)
61+
.reduce(BigInteger.ONE, BigInteger::multiply);
62+
}
63+
64+
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package com.stackify.threadpools;
2+
3+
import java.math.BigInteger;
4+
import java.util.concurrent.Callable;
5+
import java.util.concurrent.ExecutionException;
6+
import java.util.concurrent.Executor;
7+
import java.util.concurrent.ExecutorService;
8+
import java.util.concurrent.Executors;
9+
import java.util.concurrent.ForkJoinPool;
10+
import java.util.concurrent.Future;
11+
import java.util.concurrent.LinkedBlockingQueue;
12+
import java.util.concurrent.ScheduledExecutorService;
13+
import java.util.concurrent.ScheduledThreadPoolExecutor;
14+
import java.util.concurrent.ThreadPoolExecutor;
15+
import java.util.concurrent.TimeUnit;
16+
17+
import org.slf4j.Logger;
18+
import org.slf4j.LoggerFactory;
19+
20+
import com.stackify.models.Employee;
21+
import com.stackify.services.EmployeeService;
22+
23+
public class ThreadsApplication {
24+
25+
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
26+
27+
public static void main(String[] args) {
28+
testExecutor();
29+
testExecutorService();
30+
testScheduledExecutorService();
31+
testThreadPoolExecutor();
32+
testForkJoinPool();
33+
}
34+
35+
private static EmployeeService employeeService = new EmployeeService();
36+
37+
public static void testExecutor() {
38+
Executor executor = Executors.newSingleThreadExecutor();
39+
executor.execute(() -> System.out.println("Single thread pool test"));
40+
}
41+
42+
public static void testExecutorService() {
43+
44+
Employee employee = new Employee("John", 2000);
45+
46+
ExecutorService executor = Executors.newFixedThreadPool(10);
47+
48+
Callable<Double> callableTask = () -> {
49+
return employeeService.calculateBonus(employee);
50+
};
51+
Future<Double> future = executor.submit(callableTask);
52+
53+
try {
54+
if (future.isDone()) {
55+
double result = future.get();
56+
System.out.println("Bonus is:" + result);
57+
}
58+
} catch (InterruptedException | ExecutionException e) {
59+
e.printStackTrace();
60+
}
61+
62+
executor.shutdown();
63+
}
64+
65+
public static void testScheduledExecutorService() {
66+
Employee employee = new Employee("John", 2000);
67+
68+
ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
69+
70+
Callable<Double> callableTask = () -> {
71+
return employeeService.calculateBonus(employee);
72+
};
73+
74+
Future<Double> futureScheduled = executor.schedule(callableTask, 2, TimeUnit.MILLISECONDS);
75+
76+
try {
77+
System.out.println("Bonus:" + futureScheduled.get());
78+
} catch (InterruptedException | ExecutionException e) {
79+
e.printStackTrace();
80+
}
81+
82+
executor.scheduleAtFixedRate(() -> System.out.println("Fixed Rate Scheduled"), 2, 2000, TimeUnit.MILLISECONDS);
83+
executor.scheduleWithFixedDelay(() -> System.out.println("Fixed Delay Scheduled"), 2, 2000, TimeUnit.MILLISECONDS);
84+
}
85+
86+
public static void testThreadPoolExecutor() {
87+
ThreadPoolExecutor fixedPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
88+
ThreadPoolExecutor cachedPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
89+
90+
ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 6, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
91+
executor.setMaximumPoolSize(8);
92+
93+
ScheduledThreadPoolExecutor scheduledExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);
94+
}
95+
96+
public static void testForkJoinPool() {
97+
ForkJoinPool pool = ForkJoinPool.commonPool();
98+
logger.info("Thread Pool Created");
99+
BigInteger result = pool.invoke(new FactorialTask(100));
100+
System.out.println(result.toString());
101+
}
102+
}

0 commit comments

Comments
 (0)