Java 21 : Record Patterns, Pattern Matching and Virtual Threads

Java 21 release brings along with it new features which are very much programmer friendly and helps developer to reduce the amount of code to achieve same functionality. In this article, we will go through three of these features – Record Patterns, Pattern Matching for switch and Virtual Threads.

Record Patterns

This feature helps in writing more concise code when dealing with scenarios where you have methods which can get different kinds of records and you need to conditionally accessing the information from the input.

Prior to Java 21
if(inputObject instanceof CustomRecord cr) {
  System.out.println(cr.var1());
  System.out.println(cr.var2());
}
After Java 21
if(inputObject instanceof CustomRecord cr (int var1, String var2)) {
  System.out.println(var1);
  System.out.println(var2);
}

Pattern Matching for switch

Consider you have same requirement as above but this time you can even use switch expression as part of Java 21 which was not possible in previous versions.

Prior to Java 21
if(inputObject instanceof UserRecord user) {
  System.out.println(user.name());
}else if(inputObject instanceof AddressRecord addr) {
  System.out.println(addr.location());
}
After Java 21
switch(inputObject) {
  case UserRecord user -> System.out.println(user.name());
  case AddressRecord addr -> System.out.println(addr.location());
}

Virtual Threads

This feature helps you to write high-throughput concurrent applications. Virtual thread are much more lightweight in comparison to regular threads ending up consuming very less memory. You can spawn much larger number of virtual threads in comparison to regular thread given same amount of memory limit.

Below is a simple example which creates 10 virtual threads and print their thread Ids.
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
		int counter = 10;
		
		while (counter > 0) {
			executor.submit(() -> System.out.println(Thread.currentThread().threadId()));
			counter--;
		}
		executor.close();

Leave a Comment

Your email address will not be published. Required fields are marked *