Skip to content

Commit 105e387

Browse files
author
alican akkus
committed
added concurrency examples
1 parent da2ddfa commit 105e387

File tree

6 files changed

+295
-0
lines changed

6 files changed

+295
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.caysever.java8.concurrency;
2+
3+
import java.util.List;
4+
import java.util.concurrent.Callable;
5+
import java.util.concurrent.ExecutorService;
6+
import java.util.concurrent.Executors;
7+
import java.util.concurrent.Future;
8+
import java.util.concurrent.TimeUnit;
9+
import java.util.stream.Collectors;
10+
11+
import com.caysever.java8.model.Person;
12+
import com.caysever.java8.utils.PersonUtil;
13+
14+
/**
15+
* @author alican
16+
*
17+
*/
18+
public class CallableExample {
19+
20+
public static void main(String[] args) {
21+
22+
try {
23+
List<Person> persons = PersonUtil.mockPersons();
24+
25+
//Callables are functional interfaces just like runnables but instead of being void they return a value.
26+
Callable<List<Person>> personsSortingAndFilteringTask = () -> {
27+
try {
28+
TimeUnit.SECONDS.sleep(3);
29+
return persons.stream().sorted((p1, p2) -> p1.getBirthday().compareTo(p2.getBirthday())).filter((p) -> p.getFirstname() != null)
30+
.collect(Collectors.toList());
31+
} catch (InterruptedException e) {
32+
throw new IllegalStateException("task interrupted", e);
33+
}
34+
};
35+
36+
ExecutorService executor = Executors.newFixedThreadPool(1);
37+
Future<List<Person>> future = executor.submit(personsSortingAndFilteringTask);
38+
39+
//executor.shutdownNow(); dont call this method in this point. executor and callable-future is tightly coupled.
40+
41+
System.out.println("future done? " + future.isDone());
42+
43+
List<Person> resultOfPersonsTask = future.get();
44+
executor.shutdownNow();// we can shutdown now
45+
46+
System.out.println("future done? " + future.isDone());
47+
48+
resultOfPersonsTask.forEach(System.out::println);
49+
50+
} catch (Exception e) {
51+
e.printStackTrace();
52+
}
53+
}
54+
55+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.caysever.java8.concurrency;
2+
3+
import java.util.List;
4+
import java.util.concurrent.ExecutorService;
5+
import java.util.concurrent.Executors;
6+
import java.util.concurrent.TimeUnit;
7+
8+
import com.caysever.java8.model.Person;
9+
import com.caysever.java8.utils.PersonUtil;
10+
11+
/**
12+
* @author alican
13+
*
14+
*/
15+
public class ExecutorsExample {
16+
17+
public static void main(String[] args) {
18+
19+
try {
20+
List<Person> persons = PersonUtil.mockPersons();
21+
22+
ExecutorService executor = Executors.newSingleThreadExecutor();
23+
executor.submit(() -> {
24+
String threadName = Thread.currentThread().getName();// pool-1-thread-1
25+
persons.forEach((p) -> System.out.println(threadName + " | " + p));
26+
});
27+
28+
executor.submit(() -> {
29+
String threadName = Thread.currentThread().getName();// pool-1-thread-1
30+
persons.forEach((p) -> System.err.println(threadName + " | " + p));
31+
});
32+
33+
// the java process never stops!
34+
35+
// executor.shutdown();// Executors have to be stopped explicitly -
36+
// waits
37+
// for currently running tasks to finish
38+
39+
// executor.shutdownNow();// interrupts all running tasks and shut
40+
// the executor down immediately.
41+
42+
// or you can this;
43+
System.out.println("attempt to shutdown executor in 15 seconds");
44+
executor.awaitTermination(15, TimeUnit.SECONDS);
45+
46+
} catch (InterruptedException e) {
47+
e.printStackTrace();
48+
}
49+
}
50+
51+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.caysever.java8.concurrency;
2+
3+
import java.util.List;
4+
import java.util.concurrent.Callable;
5+
import java.util.concurrent.ExecutorService;
6+
import java.util.concurrent.Executors;
7+
import java.util.concurrent.Future;
8+
import java.util.concurrent.TimeUnit;
9+
import java.util.concurrent.TimeoutException;
10+
import java.util.stream.Collectors;
11+
12+
import com.caysever.java8.model.Person;
13+
import com.caysever.java8.utils.PersonUtil;
14+
15+
/**
16+
* @author alican
17+
*
18+
*/
19+
public class FutureTimeoutsExample {
20+
21+
public static void main(String[] args) {
22+
23+
try {
24+
List<Person> persons = PersonUtil.mockPersons();
25+
26+
//Callables are functional interfaces just like runnables but instead of being void they return a value.
27+
Callable<List<Person>> personsSortingAndFilteringTask = () -> {
28+
try {
29+
TimeUnit.SECONDS.sleep(3);
30+
return persons.stream().sorted((p1, p2) -> p1.getBirthday().compareTo(p2.getBirthday())).filter((p) -> p.getFirstname() != null)
31+
.collect(Collectors.toList());
32+
} catch (InterruptedException e) {
33+
throw new IllegalStateException("task interrupted", e);
34+
}
35+
};
36+
37+
ExecutorService executor = Executors.newFixedThreadPool(1);
38+
Future<List<Person>> future = executor.submit(personsSortingAndFilteringTask);
39+
40+
41+
42+
try{
43+
List<Person> resultOfPersonsTask = future.get(1, TimeUnit.SECONDS);//we should getting timeout exception
44+
resultOfPersonsTask.forEach(System.out::println);
45+
}catch(TimeoutException te){
46+
te.printStackTrace();
47+
//java.util.concurrent.TimeoutException
48+
// at java.util.concurrent.FutureTask.get(FutureTask.java:205)
49+
// at
50+
// com.caysever.java8.concurrency.FutureTimeoutsExample.main(FutureTimeoutsExample.java:43)
51+
52+
}finally{
53+
executor.shutdownNow();
54+
}
55+
56+
57+
} catch (Exception e) {
58+
e.printStackTrace();
59+
}
60+
}
61+
62+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.caysever.java8.concurrency;
2+
3+
import java.util.Arrays;
4+
import java.util.List;
5+
import java.util.concurrent.Callable;
6+
import java.util.concurrent.ExecutorService;
7+
import java.util.concurrent.Executors;
8+
import java.util.stream.Collectors;
9+
10+
import com.caysever.java8.model.Person;
11+
import com.caysever.java8.utils.PersonUtil;
12+
13+
/**
14+
* @author alican
15+
*
16+
*/
17+
public class MultipleCallablesExample {
18+
19+
public static void main(String[] args) {
20+
21+
try {
22+
List<Person> persons = PersonUtil.mockPersons();
23+
24+
//create callable list which return sorted persons
25+
List<Callable<List<Person>>> callables = Arrays.asList(() -> {
26+
System.out.println("Persons sorting by birthday..");
27+
return persons.stream().sorted((p1, p2) -> p1.getBirthday().compareTo(p2.getBirthday())).collect(Collectors.toList());
28+
}, () -> {
29+
System.out.println("Persons sorting by firstname..");
30+
return persons.stream().sorted((p1, p2) -> p1.getFirstname().compareTo(p2.getFirstname())).collect(Collectors.toList());
31+
}, () -> {
32+
System.out.println("Persons sorting by lastname..");
33+
return persons.stream().sorted((p1, p2) -> p1.getLastname().compareTo(p2.getLastname())).collect(Collectors.toList());
34+
});
35+
36+
//create work stealing pool for more than one tasks
37+
ExecutorService executor = Executors.newWorkStealingPool();
38+
39+
executor.invokeAll(callables).stream().map(future -> {
40+
try {
41+
return future.get();
42+
} catch (Exception e) {
43+
throw new IllegalStateException(e);
44+
}
45+
}).forEach(System.out::println);
46+
47+
//executor.invokeAny(callables).forEach(System.out::println); // call the invokeAny function for returns the string result of the fastest callable
48+
49+
} catch (Exception e) {
50+
e.printStackTrace();
51+
}
52+
}
53+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.caysever.java8.concurrency;
2+
3+
import java.time.LocalDateTime;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.ScheduledExecutorService;
6+
import java.util.concurrent.TimeUnit;
7+
8+
/**
9+
* @author alican
10+
*
11+
*/
12+
public class ScheduledExecutorsExample {
13+
14+
public static void main(String[] args) {
15+
16+
try {
17+
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
18+
19+
//print time with every second
20+
Runnable task = () -> {
21+
System.out.println("Current date time: " + LocalDateTime.now());
22+
};
23+
24+
executor.scheduleAtFixedRate(task,0, 1, TimeUnit.SECONDS);//0: initial delay, 1: period
25+
26+
} catch (Exception e) {
27+
e.printStackTrace();
28+
}
29+
}
30+
31+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.caysever.java8.concurrency;
2+
3+
import java.util.List;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.ScheduledExecutorService;
6+
import java.util.concurrent.ScheduledFuture;
7+
import java.util.concurrent.TimeUnit;
8+
9+
import com.caysever.java8.model.Person;
10+
import com.caysever.java8.utils.PersonUtil;
11+
12+
/**
13+
* @author alican
14+
*
15+
*/
16+
public class ScheduledFixedRateExecutorsExample {
17+
18+
public static void main(String[] args) {
19+
20+
try {
21+
List<Person> persons = PersonUtil.mockPersons();
22+
23+
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
24+
25+
Runnable task = () -> {
26+
String threadName = Thread.currentThread().getName();// pool-1-thread-1
27+
persons.forEach((p) -> System.out.println(threadName + " | " + p));
28+
};
29+
30+
ScheduledFuture<?> future = executor.schedule(task, 3, TimeUnit.SECONDS);
31+
32+
long remainingDelay = future.getDelay(TimeUnit.MILLISECONDS);
33+
System.out.printf("Remaining Delay: %sms", remainingDelay);//remaining time almost is 2.99 second
34+
System.out.println();
35+
36+
executor.shutdown();
37+
38+
} catch (Exception e) {
39+
e.printStackTrace();
40+
}
41+
}
42+
43+
}

0 commit comments

Comments
 (0)