1

Project Loom’s Scoped Values: The Most Interesting New Java 20 Feature

 1 year ago
source link: https://devm.io/java/java-20-features
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Interview with Sven Woltmann about new features in Java 20

Project Loom’s Scoped Values: The Most Interesting New Java 20 Feature


What innovations does Java 20 bring? Sven Woltmann, a Java expert, explains the exciting features of Java 20 and highlights why scoped values are particularly interesting with an illustrative application example. Furthermore, Sven provides a glimpse into what Java 21 has in store.

devmio: Hi Sven, thank you for taking the time to answer our questions. You have extensive knowledge and experience in Java and its related technologies. Could you tell us what the most interesting features in Java 20 are?

Sven Woltmann: That is definitely “Scoped Values” (JEP 429) — the third preview feature from Project Loom, which already gave us virtual threads and “Structured Concurrency” in Java 19.

Scoped Values allow us to make a value (any object) available for a limited period of time so that it can only be read in the thread that wrote the value. It’s very similar to ThreadLocal variables, but more modern and robust.

devmio: Could you give us a usage example of this?

Sven Woltmann: The classic example is user information during the execution of a request by a web server. Once a user is authenticated, their data can be stored in a “scope”, and methods for further request processing are called within this scope.

In these methods, user information can be accessed at any time via a static ScopedValue field without having to pass it through from method to method. After the called methods have finished, the scope ends and the stored object is released for garbage collection (unless it is referenced elsewhere). This prevents memory leaks, which is a common problem with improperly used ThreadLocal variables.

Scoped Values are also immutable, which greatly improves code readability, robustness, and maintainability. They also work with virtual threads and can be inherited by child threads through Structured Concurrency. Unlike with InheritableThreadLocal, they are not copied, which is a significant memory saver when you’re using millions of virtual threads.

You can find a detailed code example on my blog: https://www.happycoders.eu/de/java/scoped-values/.

devmio: Which new features do you find especially useful?

Sven Woltmann: With the second preview of Record Patterns (JEP 432), you can now also use them in for loops, like this:

for (Position(int x, int y) : positions) {
  System.out.printf("Position: (%d, %d)%n", x, y);
}

Also, under “Other Changes”, there’s a useful new compiler warning that warns us of unwanted casts when a compound assignment operator is used. Most developers are surprised that the following code leads to a compiler error:

GraalVM Day

GraalVM Day

At GraalVM Day, four experts will show you why it is worthwhile to use GraalVM, which areas of application it covers, and which best practices are already emerging. Join the revolution!

short a = 1;
a = a + 1;

The reason is that the addition’s result is an int, which cannot be assigned to a short variable without an explicit cast. This makes sense, because if the addition’s result was longer than 16 bits, information would be lost by the cast.

However, the compiler does allow the following:

short a = 1;
a += 1;

Isn't that the same thing? No! In a compound assignment operator, the compiler implicitly inserts a cast. The second example corresponds to the following code:

short a = 1;
a = (short) (a + 1);

We see this become a serious problem when we use other values:

short a = 30_000;
a += 50_000;

The variable a does not have the value 80,000 at the end, but 14,464.

This doesn’t change in Java 20. But the compiler (if it is called with -Xlint) now issues the following warning:

warning: [lossy-conversions] implicit cast from int to short in compound assignment is possibly lossy

This avoids many errors from the outset, which may otherwise only occur in production.

devmio: What are your expectations for Java 21?

Sven Woltmann: I hope that many preview features from Project Loom (“Virtual Threads”, “Structured Concurrency”, and “Scoped Values”) and Project Amber (“Pattern Matching for switch” and “Record Patterns”) will be finalized. And I hope that I can get my customers to upgrade to Java 21 as soon as possible.

I'm also looking forward to the new SequencedCollection interface, which will allow you to easily access the first and last elements of a List, LinkedHashSet, or LinkedHashMap using getFirst() and getLast().

devmio: Could you please provide some information about your background and your work for those that are not familiar with you?

Seven Woltmann: I have been a passionate programmer since childhood. As a computer science student in 1996, I read about the then brand new programming language Java. I was immediately enthusiastic and decided to implement my study projects with Java from then on.

During my studies, I worked for Telebuch.de, where we used the first Java-based web server, JRun. Telebuch was later acquired by Amazon, and I was able to experience the dot-com boom of 1998/99 firsthand for a few months at Amazon’s headquarters in Seattle.

After graduating, I founded my own startups with partners, first in Los Angeles and then — after the dot-com bubble burst — back in Germany. One of those startups was acquired by 1&1, and I was tasked with re-implementing the messaging backbone for the parent company United Internet — in Java, of course.

Since 2019, I have been working independently as a developer and coach, focusing on highly scalable Java enterprise applications. I’m mostly booked by clients who are struggling with performance and scalability issues in complex brownfield monoliths.

I help fix the acute problems in the existing code and transform the monolith into a modern, service-oriented landscape using DDD principles and better maintainable architectures. In the process, I also train developer teams in coaching and training sessions specifically tailored to the business.

In my private life, I enjoy big city life in Berlin with my wife and children and the sun of the Canary Islands during winter months.

devmio: What was the most difficult Java project you worked on?

Sven Woltmann: It was a decade-plus old Java 7-based monolith (Java 13 had just come out at the time) with over 100 Maven modules, extremely high coupling between modules, and compile times that were long enough for a coffee break.

When I joined the project, the Monolith needed to be restarted several times a week with 20-minutes of customer downtime after an increased workload kept maneuvering it into various livelock situations, where it couldn’t recover from without a restart.

First, I analyzed and fixed the acute problems. Then, I extended the code base through distributed synchronization to enable zero-downtime deployment with multiple instances.

devmio: Thank you for the interview!

Sven Woltmann
Sven Woltmann

Sven Woltmann is a passionate Java programmer. After studying computer science, he worked for two decades as a lead programmer and CTO for various companies – from startups to corporations. His focus is on scalable enterprise applications, optimization of algorithms, clean code and clean architecture. Since 2019 he has been working as an independent developer, coach and course instructor. He also shares his knowledge about Java, architecture, algorithms and data structures in videos, his newsletter and on his blog: https://www.happycoders.eu/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK