This month we are focusing on OpenJDK projects you should know about. This time we will be covering Valhalla. We have also looked at Panama, Loom, Skara and Amber.
Project Valhalla was started back in 2014 by the HotSpot Group. It proposes to introduce some changes into the way types can be used in Java.
There are 3 main goals of Project Valhalla (defined on the wiki page):
- Align JVM memory layout behaviour with the cost model of modern hardware;
- Extend generics to allow abstraction over all types, including primitives, values, and even void;
- Enable existing libraries — especially the JDK — to compatibly evolve to fully take advantage of these features.
So Valhalla is partly about improving Java as a language and partly to change the way Java works to take advantage of modern hardware changes since Java was introduced in 1995 – a long time ago in technical terms when we live with Moore’s law.
Among other proposed changes, there are 2 Java Enhancement Proposals that propose will mark a major change:
1. Value Objects
Value types (like primitive types, such as int, boolean, char etc) provide better performance than reference types. Value types are the actual value, whereas reference types are references to another value.
One of the aims of Project Valhalla is to be able to create Value Objects, which will behave in a similar way to primitive types but can be defined by the user.
The aim of this JEP is to define a new operator called lockPermanently. This will take an object and returns it in a permanently immutable state. The benefit of this will be that they will be cheaper to work with, like primitive types.
This technique will be applied to wrapper types such as Integer and Boolean.
2. Generics over Primitive Types
One of the limitations of Generics in Java is that they can only be used with reference types (types that extend Object) and not primitive types. This would also mean that once value types were introduced, you would not be able to use them as arguments for Generic classes.
For example if I have a class called Test that looks like this:
public class Test<T> {
.......
}
I can do this:
Test<Integer> test = new Test<>();
But not this:
Test<int> test = new Test<>();
The main disadvantages of having to use a boxed type such as Integer is that it is more costly. Project Valhalla proposes to use specialization to allow primitives like int to be used instead, which means that there will no longer be the memory overhead. And, you will be able to pass in value types.
What are your thoughts on Project Valhalla? Let us know in the comments.