-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathJava21Features.java
More file actions
276 lines (244 loc) · 10.2 KB
/
Copy pathJava21Features.java
File metadata and controls
276 lines (244 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import java.time.Duration;
import java.util.*;
import java.util.concurrent.Executors;
/**
* Java 21 Features Demonstration
* Released in September 2023 (LTS)
*
* Key Features:
* 1. Virtual Threads (Project Loom)
* 2. Pattern Matching for switch (Final)
* 3. Record Patterns (Final)
* 4. Sequenced Collections
* 5. String Templates (Preview)
*/
public class Java21Features {
// Records for pattern matching demonstration
record Point(int x, int y) {}
record Circle(Point center, int radius) {}
record Rectangle(Point topLeft, Point bottomRight) {}
public static void main(String[] args) {
demonstrateVirtualThreads();
demonstratePatternMatching();
demonstrateRecordPatterns();
demonstrateSequencedCollections();
}
/**
* Virtual Threads - lightweight threads for high-throughput concurrent applications
* Note: Virtual threads require Java 21+
*/
private static void demonstrateVirtualThreads() {
System.out.println("=== Java 21: Virtual Threads ===");
System.out.println("Virtual threads are lightweight threads introduced in Java 21");
System.out.println("They enable high-throughput concurrent applications.");
System.out.println();
// Java 21 syntax (requires Java 21+):
/*
// Create and start a virtual thread
Thread vThread = Thread.ofVirtual().start(() -> {
System.out.println("Hello from virtual thread: " + Thread.currentThread());
});
try {
vThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// Using virtual thread executor
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 5; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("Task " + taskId + " running on: " + Thread.currentThread());
return taskId;
});
}
} // executor.close() is called automatically
*/
// Demonstration using traditional threads
Thread traditionalThread = new Thread(() -> {
System.out.println("Traditional thread: " + Thread.currentThread().getName());
});
traditionalThread.start();
try {
traditionalThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Virtual threads can be created in millions (vs thousands for platform threads)");
System.out.println();
}
/**
* Pattern Matching for switch - now a standard feature
*/
private static void demonstratePatternMatching() {
System.out.println("=== Java 21: Pattern Matching for switch ===");
Object[] testObjects = {
"Hello World",
42,
3.14159,
List.of("A", "B", "C"),
null
};
for (Object obj : testObjects) {
String result = describeWithPatternMatching(obj);
System.out.println(obj + " -> " + result);
}
System.out.println();
}
private static String describeWithPatternMatching(Object obj) {
// Pattern matching for switch with type patterns and guards
// Note: This uses Java 17 compatible syntax
// In Java 21, you can use: case String s when s.length() > 10 -> ...
if (obj == null) {
return "It's null";
} else if (obj instanceof String s) {
if (s.length() > 10) {
return "Long string: " + s.substring(0, 10) + "...";
}
return "String: " + s;
} else if (obj instanceof Integer i) {
if (i > 100) {
return "Large integer: " + i;
}
return "Integer: " + i;
} else if (obj instanceof Double d) {
return "Double: " + d;
} else if (obj instanceof List<?> list) {
return "List of size " + list.size();
} else {
return "Unknown: " + obj.getClass().getSimpleName();
}
// Java 21 syntax (requires Java 21+):
/*
return switch (obj) {
case null -> "It's null";
case String s when s.length() > 10 -> "Long string: " + s.substring(0, 10) + "...";
case String s -> "String: " + s;
case Integer i when i > 100 -> "Large integer: " + i;
case Integer i -> "Integer: " + i;
case Double d -> "Double: " + d;
case List<?> list -> "List of size " + list.size();
default -> "Unknown: " + obj.getClass().getSimpleName();
};
*/
}
/**
* Record Patterns - destructuring records in pattern matching
*/
private static void demonstrateRecordPatterns() {
System.out.println("=== Java 21: Record Patterns ===");
Object[] shapes = {
new Circle(new Point(0, 0), 5),
new Rectangle(new Point(0, 0), new Point(10, 10)),
new Point(3, 4)
};
for (Object shape : shapes) {
String description = describeShape(shape);
System.out.println(description);
}
System.out.println();
}
private static String describeShape(Object obj) {
// Java 17 compatible approach - manual destructuring
if (obj instanceof Circle c) {
Point center = c.center();
return String.format("Circle at (%d,%d) with radius %d",
center.x(), center.y(), c.radius());
} else if (obj instanceof Rectangle r) {
Point topLeft = r.topLeft();
Point bottomRight = r.bottomRight();
return String.format("Rectangle from (%d,%d) to (%d,%d)",
topLeft.x(), topLeft.y(), bottomRight.x(), bottomRight.y());
} else if (obj instanceof Point p) {
return String.format("Point at (%d,%d)", p.x(), p.y());
}
return "Unknown shape";
// Java 21 syntax with record patterns (requires Java 21+):
// Record patterns allow you to destructure records directly in the pattern
/*
return switch (obj) {
case Circle(Point(int x, int y), int r) ->
String.format("Circle at (%d,%d) with radius %d", x, y, r);
case Rectangle(Point(int x1, int y1), Point(int x2, int y2)) ->
String.format("Rectangle from (%d,%d) to (%d,%d)", x1, y1, x2, y2);
case Point(int x, int y) ->
String.format("Point at (%d,%d)", x, y);
default -> "Unknown shape";
};
*/
}
/**
* Sequenced Collections - collections with defined encounter order
* Note: Sequenced Collections require Java 21+
*/
private static void demonstrateSequencedCollections() {
System.out.println("=== Java 21: Sequenced Collections ===");
System.out.println("Java 21 introduces SequencedCollection interface with methods:");
System.out.println(" - getFirst() / getLast()");
System.out.println(" - addFirst() / addLast()");
System.out.println(" - removeFirst() / removeLast()");
System.out.println(" - reversed()");
System.out.println();
// Java 17 compatible demonstration
List<String> list = new ArrayList<>(List.of("First", "Middle", "Last"));
// Traditional way to access first and last elements
System.out.println("First element (Java 17): " + list.get(0));
System.out.println("Last element (Java 17): " + list.get(list.size() - 1));
// Traditional way to add to beginning or end
list.add(0, "New First");
list.add("New Last");
System.out.println("After adding: " + list);
// Traditional way to remove from beginning or end
list.remove(0);
list.remove(list.size() - 1);
System.out.println("After removing: " + list);
// Manual reversal
List<String> reversed = new ArrayList<>();
for (int i = list.size() - 1; i >= 0; i--) {
reversed.add(list.get(i));
}
System.out.println("Reversed (Java 17): " + reversed);
System.out.println();
System.out.println("Java 21 syntax (requires Java 21+):");
System.out.println(" list.getFirst() // Instead of list.get(0)");
System.out.println(" list.getLast() // Instead of list.get(list.size()-1)");
System.out.println(" list.addFirst(e) // Instead of list.add(0, e)");
System.out.println(" list.reversed() // Returns a reversed view");
/*
// Java 21+ code:
List<String> list = new ArrayList<>(List.of("First", "Middle", "Last"));
System.out.println("First element: " + list.getFirst());
System.out.println("Last element: " + list.getLast());
list.addFirst("New First");
list.addLast("New Last");
System.out.println("After adding: " + list);
list.removeFirst();
list.removeLast();
System.out.println("After removing: " + list);
System.out.println("Reversed: " + list.reversed());
LinkedHashSet<String> set = new LinkedHashSet<>(List.of("A", "B", "C"));
System.out.println("Set first: " + set.getFirst());
System.out.println("Set last: " + set.getLast());
System.out.println("Set reversed: " + set.reversed());
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
System.out.println("Map first entry: " + map.firstEntry());
System.out.println("Map last entry: " + map.lastEntry());
System.out.println("Map reversed: " + map.reversed());
*/
System.out.println();
}
/**
* Sample record for demonstration
*/
record Person(String name, int age) {
// Compact constructor
public Person {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
}
}