Quarkus is a very popular Java application development framework. It is positioned as a lightweight micro-service framework. Quarkus provides excellent container integration capabilities, compared to the traditional development framework (Spring Boot) has a faster startup speed, less memory consumption, shorter service response.
The Quarkus project is packaged as a native running program through GraalVM, that is, the project can be started quickly, reaching the second level or even the millisecond level.
But in the process of use also has certain constraints, such as random number. In the original way the project was packaged as a JAR, the loading and initialization of the classes were performed when the program was running. For example, the generation of Random seeds in the java.util.random class was generated when the program was actually running and initialized. But when GraalVM packages Quarkus as a native program to run, it initializes the static properties in the class directly, rather than waiting for the program to run.
Suppose you happen to define and create a java.util.Random object in a static property of the class
private static final Random RANDOM = new Random();
Copy the code
Then you will report the following error:
This is because GraalVM packaging initializes Random objects and Random seeds and verifies that such encoding is not allowed.
There are two official solutions to this problem: 1. He advises you to change the code logic to not initialize the Random object in the static property of the class. The initialization and use of the object is achieved by using the singleton pattern.
public class RandomUtil { private static Random random; public static Random get() { if (random == null) { synchronized (RandomUtil.class) { if (random == null) { random = new Random(); } } } return random; }}Copy the code
If you do not want to change your writing, or if the problem is a third party JAR and you cannot change the source code, then the official provides a way to initialize at run time. You can solve this problem by specifying the classes that need to be initialized at run time. Add configuration in the application.properties file:
# delay initialization org.apache.com mons. Lang3. RandomStringUtils class quarkus.native.additional-build-args=--initialize-at-run-time=org.apache.commons.lang3.RandomStringUtilsCopy the code
Note that the class that contains the Random static property is written here, not the Random class.
In fact, Quarkus official itself also encountered this problem, and they solved it through coding, not through parameter configuration. Merge pull Request #16008 from Zakkak/GRPC-random-Reinit
Finally, thanks for reading. May your life be bug-free.