Yes, Java ThreadLocalRandom is Safe to Use with Virtual Threads

Because Java 21 virtual threads are very cheap — per JEP Cafe, they are about 1,000 times faster to launch than a platform thread, and use about 1,000 times less memory than a platform thread — they should never be pooled. As a result, ThreadLocal variables are unlikely to be useful in applications that use virtual threads for concurrent processing. If each task lives in its own dedicated thread, then each call to ThreadLocal ends up returning a new value, and it ends up being a factory instead of a pool! So using ThreadLocal in virtual threads is an anti-pattern. Developers should use another technique for pooling objects, such as structured concurrency, instead.

But what about ThreadLocalRandom? Is this dedicated class for providing sources of randomness to threads safe to use with virtual threads?

The short answer is: Yes, ThreadLocalRandom is safe to use with virtual threads. ThreadLocalRandom is tightly integrated with the Thread class to ensure that it remains efficient, even for virtual threads. For more information, keep reading.

Continue reading “Yes, Java ThreadLocalRandom is Safe to Use with Virtual Threads”

Community-Managed AWS Lambda Base Images for Java 21

I’ve added a new custom base image for Java 21 on Lambda to complement the community base images already available for Java 17, Java 18, Java 19, and Java 20. You can find the images on the ECR Public Gallery and DockerHub and the source code on GitHub. Java 21 is an LTS release with some of the most exciting new features Java has seen in a long time, so everyone should be looking to upgrade ASAP!

I’ve also released a custom Lambda runtime for Java 21, if that’s more your speed.

These should be plenty to get you started on your AWS Lambda + Java 21 adventure!

Continue reading “Community-Managed AWS Lambda Base Images for Java 21”

Java 21 Custom Runtime for AWS Lambda

By standing on the shoulders of giants (I’m looking at you, Mark Sailes), I was able to turn around an AWS Lambda Custom Runtime for Java 21 on Java 21 launch day. Instructions to use it are in the repo’s README. All files required to create your own function are in the releases, so no building required.

There are a couple of known issues, particularly around CDS (Class Data Sharing), per the but they appear to be (mostly) cosmetic at first blush. It’ll be fun ironing that out.

I’m also looking forward to releasing a custom image for Java 21, too, as soon as an updated Amazon Corretto image drops.

Happy hacking!