Skip to content

Commit 01d7e21

Browse files
Java 21 Programs
1 parent bb38c5e commit 01d7e21

File tree

8 files changed

+321
-37
lines changed

8 files changed

+321
-37
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Java 21 Tutorials
2+
3+
- [Java 21 Unnamed Patterns and Variables (with Examples)](https://howtodoinjava.com/java/unnamed-patterns-and-variables/)
4+
- [Java 21 Scoped Values: A Deep Dive with Examples](https://howtodoinjava.com/java/multi-threading/java-scoped-values/)
5+
- [Java Record Patterns and Pattern Matching](https://howtodoinjava.com/java/record-patterns-and-pattern-matching/)
6+
- [Java Unnamed Classes and Instance Main Methods](https://howtodoinjava.com/java/java-unnamed-class-instance-method/)
7+
- [Java 21 Sequenced Collections](https://howtodoinjava.com/java/sequenced-collections/)
8+
- [Java 21 Features: Practical Examples and Insights](https://howtodoinjava.com/java/java-21-new-features/)
9+
- [Java 21 String Templates](https://howtodoinjava.com/java/java-string-templates/)
10+
- [Java 21 Structured Concurrency: StructuredTaskScope](https://howtodoinjava.com/java/multi-threading/structured-concurrency/)
11+
- [Java Virtual Threads – Project Loom](https://howtodoinjava.com/java/multi-threading/virtual-threads/)

src/main/java/com/howtodoinjava/newFeatures/java21/ScopedValueTest.java

Lines changed: 29 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,58 @@
11
package com.howtodoinjava.newFeatures.java21;
22

3-
//import java.util.concurrent.StructuredTaskScope;
3+
import java.util.concurrent.StructuredTaskScope;
44

55
public class ScopedValueTest {
66

77
//public static ThreadLocal<String> CONTEXT = ThreadLocal.withInitial(() -> null);
8-
//public static InheritableThreadLocal<String> CONTEXT = new InheritableThreadLocal();
9-
10-
//private static final ScopedValue<String> CONTEXT = ScopedValue.newInstance();
11-
12-
8+
//public static InheritableThreadLocal<String> CONTEXT = new InheritableThreadLocal<>();
9+
private static final ScopedValue<String> CONTEXT = ScopedValue.newInstance();
1310

1411
public static void main(String[] args) {
1512

16-
17-
18-
/*ScopedValue.runWhere(CONTEXT, "TestValue", () -> {
13+
ScopedValue.runWhere(CONTEXT, "TestValue", () -> {
1914

2015
doSomething();
2116

2217
try (var scope = new StructuredTaskScope<String>()) {
2318

24-
scope.fork(() -> insideChildThread());
19+
scope.fork(() -> doSomethingInChildThread());
2520

26-
try{
21+
try {
2722
scope.join();
2823
} catch (InterruptedException ex) {
2924
//...
3025
}
31-
26+
3227
}
33-
});*/
28+
});
29+
}
30+
31+
static void doSomething() {
32+
System.out.println("Scoped Value in doSomething(): " + CONTEXT.get());
33+
}
34+
35+
static String doSomethingInChildThread() {
36+
System.out.println("Scoped Value in insideChildThread(): " + CONTEXT.get());
37+
return CONTEXT.get();
38+
}
3439

3540

36-
ScopedValueTest instance = new ScopedValueTest();
41+
/*ScopedValueTest instance = new ScopedValueTest();
3742
38-
/*ScopedValue.runWhere(CONTEXT, "Test Value", () -> {
43+
ScopedValue.runWhere(CONTEXT, "Test Value", () -> {
3944
4045
System.out.println("In parent thread start the scoped value is: " + CONTEXT.get());
4146
instance.doSomething();
4247
System.out.println("In parent thread end the scoped value is: " + CONTEXT.get());
4348
});
4449
4550
System.out.println("Outside bounded scope isBound() is: " + CONTEXT.isBound());
46-
System.out.println("Outside bounded scope the scoped value is: " + CONTEXT.orElse(null));*/
47-
48-
49-
50-
51-
51+
System.out.println("Outside bounded scope the scoped value is: " + CONTEXT.orElse(null));
5252
53+
Thread parentThread = new Thread(() -> {
5354
54-
55-
56-
57-
58-
59-
60-
61-
/*Thread parentThread = new Thread(() -> {
62-
63-
CONTEXT.set("TestValue");
55+
//CONTEXT.set("TestValue");
6456
insideParentThread_1();
6557
6658
Thread childThread = new Thread(() -> {
@@ -71,22 +63,22 @@ public static void main(String[] args) {
7163
insideParentThread_2();
7264
});
7365
74-
parentThread.start();*/
75-
}
66+
parentThread.start();
67+
}*/
7668

7769
/*public void doSomething() {
7870
System.out.println("In doSomething() and parent scope: " + CONTEXT.get());
7971
ScopedValue.runWhere(CONTEXT, "Changed Value", () -> {
8072
System.out.println("In doSomething() and child scope: " + CONTEXT.get());
8173
doSomethingAgain();
8274
});
83-
}*/
75+
}
8476
85-
/*public void doSomethingAgain() {
77+
public void doSomethingAgain() {
8678
System.out.println("In doSomethingAgain() and child scope: " + CONTEXT.get());
87-
}*/
79+
}
8880
89-
/*static void doSomething() {
81+
static void doSomething1() {
9082
System.out.println("Scoped Value in doSomething(): " + CONTEXT.get());
9183
}
9284
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package com.howtodoinjava.newFeatures.java21;
2+
3+
import java.util.ArrayList;
4+
import java.util.LinkedHashMap;
5+
import java.util.LinkedHashSet;
6+
import java.util.List;
7+
import java.util.Map;
8+
import java.util.TreeSet;
9+
10+
public class SequencedCollectionExamples {
11+
12+
public static void main(String[] args) {
13+
ArrayList<Integer> arrayList = new ArrayList<>();
14+
15+
arrayList.add(1); // List contains: [1]
16+
17+
arrayList.addFirst(0); // List contains: [0, 1]
18+
arrayList.addLast(2); // List contains: [0, 1, 2]
19+
20+
Integer firstElement = arrayList.getFirst(); // 0
21+
Integer lastElement = arrayList.getLast(); // 2
22+
23+
List<Integer> reversed = arrayList.reversed();
24+
System.out.println(reversed); // Prints [2, 1, 0]
25+
26+
//
27+
28+
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>(List.of(1, 2, 3));
29+
30+
firstElement = linkedHashSet.getFirst(); // 1
31+
lastElement = linkedHashSet.getLast(); // 3
32+
33+
linkedHashSet.addFirst(0); //List contains: [0, 1, 2, 3]
34+
linkedHashSet.addLast(4); //List contains: [0, 1, 2, 3, 4]
35+
36+
System.out.println(linkedHashSet.reversed()); //Prints [5, 3, 2, 1, 0]
37+
38+
//
39+
40+
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
41+
42+
map.put(1, "One");
43+
map.put(2, "Two");
44+
map.put(3, "Three");
45+
46+
map.firstEntry(); //1=One
47+
map.lastEntry(); //3=Three
48+
49+
System.out.println(map); //{1=One, 2=Two, 3=Three}
50+
51+
Map.Entry<Integer, String> first = map.pollFirstEntry(); //1=One
52+
Map.Entry<Integer, String> last = map.pollLastEntry(); //3=Three
53+
54+
System.out.println(map); //{2=Two}
55+
56+
map.putFirst(1, "One"); //{1=One, 2=Two}
57+
map.putLast(3, "Three"); //{1=One, 2=Two, 3=Three}
58+
59+
System.out.println(map); //{1=One, 2=Two, 3=Three}
60+
System.out.println(map.reversed()); //{3=Three, 2=Two, 1=One}
61+
62+
//
63+
List<Integer> list = List.of(1, 2, 3);
64+
//list.addLast(4); //Exception in thread "main" java.lang.UnsupportedOperationException
65+
66+
TreeSet<Integer> set = new TreeSet<>(List.of(1, 2, 3));
67+
//set.addFirst(4); //Exception in thread "main" java.lang.UnsupportedOperationException
68+
69+
List<Integer> list1 = List.of();
70+
//list1.getFirst(); //Exception in thread "main" java.lang.NoSuchElementException
71+
72+
//Collections Class
73+
//Collections.unmodifiableSequencedCollection(sequencedCollection);
74+
//Collections.unmodifiableSequencedSet(sequencedSet);
75+
//Collections.unmodifiableSequencedMap(sequencedMap);
76+
}
77+
78+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.howtodoinjava.newFeatures.java21;
2+
3+
public class StringTemplates {
4+
5+
public static void main(String[] args) {
6+
String name = "Alex";
7+
String message = STR."Greetings \{name}!";
8+
System.out.println(message);
9+
10+
/*//FMT
11+
message = FMT."Greetings %-12s\{name}.";
12+
13+
//RAW
14+
StringTemplate st = RAW."Greetings \{name}.";
15+
String message = STR.process(st);*/
16+
}
17+
}
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
package com.howtodoinjava.newFeatures.java21;
2+
3+
import java.util.concurrent.ExecutionException;
4+
import java.util.concurrent.StructuredTaskScope;
5+
import java.util.function.Supplier;
6+
7+
public class StructuredConcurrency {
8+
9+
public static void main(String[] args) {
10+
StructuredConcurrency instance = new StructuredConcurrency();
11+
DemographicData data = instance.getClientDetails(1001L);
12+
//Response response = instance.getClientById(1001L);
13+
}
14+
15+
public DemographicData getClientDetails(Long id) {
16+
17+
System.out.println("Forking new threads...");
18+
19+
try (var scope = new StructuredTaskScope.ShutdownOnSuccess<>()) {
20+
21+
scope.fork(() -> fetchUserDetails(id));
22+
scope.fork(() -> fetchUserDetailsNew(id));
23+
24+
scope.join();
25+
26+
System.out.println("Response is received from a worker...");
27+
//Any one task has been completed
28+
return (DemographicData) scope.result();
29+
} catch (Exception e) {
30+
throw new RuntimeException(e);
31+
}
32+
}
33+
34+
public Response getClientById(Long id) {
35+
36+
System.out.println("Forking new threads...");
37+
38+
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
39+
40+
Supplier<AccountDetails> accountDetailsFuture = scope.fork(() -> getAccountDetails(id));
41+
Supplier<LinkedAccounts> linkedAccountsFuture = scope.fork(() -> fetchLinkedAccounts(id));
42+
Supplier<DemographicData> userDetailsFuture = scope.fork(() -> fetchUserDetails(id));
43+
44+
System.out.println("Joining all threads...");
45+
scope.join(); // Join all subtasks
46+
scope.throwIfFailed(WebApplicationException::new); //Handle error when any subtask fails
47+
48+
System.out.println("Response is received from all workers...");
49+
//The subtasks have completed by now so process the result
50+
return new Response(accountDetailsFuture.get(),
51+
linkedAccountsFuture.get(),
52+
userDetailsFuture.get());
53+
} catch (InterruptedException e) {
54+
throw new RuntimeException(e);
55+
}
56+
}
57+
58+
private DemographicData fetchUserDetails(Long id) throws InterruptedException {
59+
Thread.sleep(2000L);
60+
System.out.println("Retrieved DemographicData.");
61+
return new DemographicData();
62+
}
63+
64+
private DemographicData fetchUserDetailsNew(Long id) throws InterruptedException {
65+
Thread.sleep(1000L);
66+
System.out.println("Retrieved DemographicData from fetchUserDetailsNew.");
67+
return new DemographicData();
68+
}
69+
70+
private LinkedAccounts fetchLinkedAccounts(Long id) throws InterruptedException {
71+
Thread.sleep(3000L);
72+
System.out.println("Retrieved LinkedAccounts.");
73+
return new LinkedAccounts();
74+
}
75+
76+
private AccountDetails getAccountDetails(Long id) throws InterruptedException {
77+
Thread.sleep(4000L);
78+
System.out.println("Retrieved AccountDetails.");
79+
return new AccountDetails();
80+
}
81+
}
82+
83+
class AccountDetails {
84+
85+
}
86+
87+
class LinkedAccounts {
88+
89+
}
90+
91+
class DemographicData {
92+
93+
}
94+
95+
class Response {
96+
97+
public Response(AccountDetails accountDetails, LinkedAccounts linkedAccounts,
98+
DemographicData demographicData) {
99+
}
100+
}
101+
102+
class WebApplicationException extends RuntimeException {
103+
104+
public WebApplicationException(Throwable e) {
105+
super(e);
106+
}
107+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
void main() {
2+
System.out.println("Hello, World!");
3+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.howtodoinjava.newFeatures.java21;
2+
3+
import java.time.LocalDate;
4+
5+
public class UnnamedPatterns {
6+
7+
public static void main(String[] args) {
8+
Department department = new Department(1L, "HR", true);
9+
Employee employee = new Employee(101L, "John Doe", LocalDate.of(1990, 5, 15), true, department);
10+
11+
//With unused pattern variables
12+
if (employee instanceof Employee(Long id, String name, LocalDate dateOfBirth, Boolean status,
13+
Department(Long depId, String depName, Boolean depStatus))) {
14+
15+
System.out.printf("Employee %d works in department %s.", id, depName);
16+
}
17+
18+
if (department instanceof Department(_, String name, _)) {
19+
System.out.println("Department Name is : " + name); // Prints 'Department Name is : HR'
20+
}
21+
22+
if (employee instanceof Employee(Long id, _, _, _, Department(_, String depName, _))) {
23+
System.out.printf("Employee %d works in department %s.", id, depName);
24+
}
25+
26+
if (employee instanceof Employee(Long id, _, _, _, _)) {
27+
System.out.println("Employee Id is : " + id); // Prints 'Employee Id is : 101'
28+
}
29+
}
30+
}
31+
32+
record Department(Long id, String name, Boolean status) {
33+
// Constructor and methods (if any)
34+
}
35+
36+
record Employee(Long id, String name, LocalDate dateOfBirth, Boolean status, Department department) {
37+
// Constructor and methods (if any)
38+
}

0 commit comments

Comments
 (0)