/vibe:ghcopilot-instr-java-17-to-java-21-upgradefrom vibe
Guides upgrading Java projects from JDK 17 to JDK 21, covering pattern matching for switch, record patterns, virtual threads, and API changes.
Ships in vibe. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
These instructions help GitHub Copilot assist developers in upgrading Java projects from JDK 17 to JDK 21, focusing on new language features, API changes, and best practices.
Enhanced switch Expressions and Statements
When working with switch constructs:
// Old approach (Java 17)
public String processObject(Object obj) {
if (obj instanceof String) {
String s = (String) obj;
return s.toUpperCase();
} else if (obj instanceof Integer) {
Integer i = (Integer) obj;
return i.toString();
}
return "unknown";
}
// New approach (Java 21)
public String processObject(Object obj) {
return switch (obj) {
case String s -> s.toUpperCase();
case Integer i -> i.toString();
case null -> "null";
default -> "unknown";
};
}
switch (obj) {
case String s when s.length() > 10 -> "Long string: " + s;
case String s -> "Short string: " + s;
case Integer i when i > 100 -> "Large number: " + i;
case Integer i -> "Small number: " + i;
default -> "Other";
}
Destructuring Records in Pattern Matching
When working with records:
public record Point(int x, int y) {}
public record ColoredPoint(Point point, Color color) {}
// Destructuring in switch
public String describe(Object obj) {
return switch (obj) {
case Point(var x, var y) -> "Point at (" + x + ", " + y + ")";
case ColoredPoint(Point(var x, var y), var color) ->
"Colored point at (" + x + ", " + y + ") in " + color;
default -> "Unknown shape";
};
}
// Nested record patterns
switch (shape) {
case Rectangle(ColoredPoint(Point(var x1, var y1), var c1),
ColoredPoint(Point(var x2, var y2), var c2))
when c1 == c2 -> "Monochrome rectangle";
case Rectangle r -> "Multi-colored rectangle";
}
Lightweight Concurrency
When working with concurrency:
Thread.ofVirtual() for creating virtual threads// Old platform thread approach
ExecutorService executor = Executors.newFixedThreadPool(100);
executor.submit(() -> {
// blocking I/O operation
httpClient.send(request);
});
// New virtual thread approach
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> {
// blocking I/O operation - now scales to millions
httpClient.send(request);
});
}
// Structured concurrency (Preview)
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> user = scope.fork(() -> fetchUser(userId));
Future<String> order = scope.fork(() -> fetchOrder(orderId));
scope.join(); // Join all subtasks
scope.throwIfFailed(); // Propagate errors
return processResults(user.resultNow(), order.resultNow());
}
Safe String Interpolation
When working with string formatting:
--enable-preview// Traditional concatenation
String message = "Hello, " + name + "! You have " + count + " messages.";
// String Templates (Preview)
String message = STR."Hello, \{name}! You have \{count} messages.";
// Safe HTML generation
String html = HTML."<p>User: \{username}</p>";
// Safe SQL queries
PreparedStatement stmt = SQL."SELECT * FROM users WHERE id = \{userId}";
Enhanced Collection Interfaces
When working with collections:
SequencedCollection, SequencedSet, SequencedMap interfaces// New methods available on Lists, Deques, LinkedHashSet, etc.
List<String> list = List.of("first", "middle", "last");
String first = list.getFirst(); // "first"
String last = list.getLast(); // "last"
List<String> reversed = list.reversed(); // ["last", "middle", "first"]
// Works with any SequencedCollection
SequencedSet<String> set = new LinkedHashSet<>();
set.addFirst("start");
set.addLast("end");
String firstElement = set.getFirst();
Simplified Pattern Matching
When working with pattern matching:
_ for values you don't need// Ignore unused variables
switch (ball) {
case RedBall(_) -> "Red ball"; // Don't care about size
case BlueBall(var size) -> "Blue ball size " + size;
}
// Ignore parts of records
switch (point) {
case Point(var x, _) -> "X coordinate: " + x; // Ignore Y
case ColoredPoint(Point(_, var y), _) -> "Y coordinate: " + y;
}
// Exception handling with unnamed variables
try {
riskyOperation();
} catch (IOException | SQLException _) {
// Don't need exception details
handleError();
}
Improved Context Propagation
When working with thread-local data:
// Define scoped value
private static final ScopedValue<String> USER_ID = ScopedValue.newInstance();
// Set and use scoped value
ScopedValue.where(USER_ID, "user123")
.run(() -> {
processRequest(); // Can access USER_ID.get() anywhere in call chain
});
// In nested method
public void processRequest() {
String userId = USER_ID.get(); // "user123"
// Process with user context
}
When working with file I/O:
// Old explicit UTF-8 specification
Files.readString(path, StandardCharsets.UTF_8);
Files.writeString(path, content, StandardCharsets.UTF_8);
// New default behavior (Java 18+)
Files.readString(path); // Uses UTF-8 by default
Files.writeString(path, content); // Uses UTF-8 by default
When needing basic HTTP server:
jwebserver command or com.sun.net.httpserver enhancements// Command line
$ jwebserver -p 8080 -d /path/to/files
// Programmatic usage
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", new SimpleFileHandler(Path.of("/tmp")));
server.start();
When working with custom DNS resolution:
InetAddressResolverProvider for custom address resolutionWhen working with post-quantum cryptography:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM");
KeyPair kp = kpg.generateKeyPair();
KEM kem = KEM.getInstance("ML-KEM");
KEM.Encapsulator encapsulator = kem.newEncapsulator(kp.getPublic());
KEM.Encapsulated encapsulated = encapsulator.encapsulate();
When encountering finalize() methods:
// Deprecated finalize approach
@Override
protected void finalize() throws Throwable {
cleanup();
}
// Modern approach with Cleaner
private static final Cleaner CLEANER = Cleaner.create();
public MyResource() {
cleaner.register(this, new CleanupTask(nativeResource));
}
private static class CleanupTask implements Runnable {
private final long nativeResource;
CleanupTask(long nativeResource) {
this.nativeResource = nativeResource;
}
public void run() {
cleanup(nativeResource);
}
}
When working with agents or instrumentation:
-XX:+EnableDynamicAgentLoading to suppress warnings if neededFor projects using preview features:
--enable-preview to compiler and runtime<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<release>21</release>
<compilerArgs>
<arg>--enable-preview</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
tasks.withType<JavaCompile> {
options.compilerArgs.add("--enable-preview")
}
tasks.withType<Test> {
jvmArgs("--enable-preview")
}
For applications using Virtual Threads:
-Djdk.virtualThreadScheduler.parallelism=N # Set carrier thread count
-Djdk.virtualThreadScheduler.maxPoolSize=N # Set max pool size
When configuring garbage collection:
-XX:+UseZGC -XX:+ZGenerationalWhen reviewing code for Java 21 upgrade:
Switch Enhancement:
// From instanceof chains to switch expressions
if (obj instanceof String s) return processString(s);
else if (obj instanceof Integer i) return processInt(i);
// becomes:
return switch (obj) {
case String s -> processString(s);
case Integer i -> processInt(i);
default -> processDefault(obj);
};
Virtual Thread Adoption:
// From platform threads to virtual threads
Executors.newFixedThreadPool(200)
// becomes:
Executors.newVirtualThreadPerTaskExecutor()
Record Pattern Usage:
// From manual destructuring to record patterns
if (point instanceof Point p) {
int x = p.x();
int y = p.y();
}
// becomes:
if (point instanceof Point(var x, var y)) {
// use x and y directly
}
Remember to enable preview features only when specifically needed and test thoroughly in staging environments before deploying to production.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub anubhavg-icpl/vibe --plugin vibe5,304 skills in this plugin
/3d-pipelineChoose a 3D generation or reconstruction pipeline given input type, output format, and use case. Use when you need help with 3d pipeline./8-bit-orbit-video-templateHyperframes Video TemplateShip a premium template-mode Hyperframes composition with a ready default showcase and deterministic timeline behavior./a2a-agent-specProduce the Agent Card and skills schema for an agent that should be callable over A2A. Use when you need help with a2a agent spec.Other plugins' skills for the same job