How to generate heavy CPU load

Sometimes you need to generate heavy CPU load in your app for testing purposes.

if you are using Spring, it will be very convenient to run multi-threaded password hashing:

public void runHeavyLoad() {
    String pepper = "pepper"; // secret key used by password encoding
    int iterations = 200000; // number of hash iteration
    int hashWidth = 256; // hash with in bits
    int threadCount = 1000; // simultaneous thread count to be run

    for (int i = 0; i < threadCount; i++) {
        final int finalI = i;
        new Thread(() -> {
            while(true) {
                Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(pepper, iterations, hashWidth);
                pbkdf2PasswordEncoder.encode(UUID.randomUUID().toString());
            }
        }).start();
    }
}

That code is non-blocking, so your program are not going to pause. If you want to pause, you may add the line to the end of runHeavyLoad() method:

Thread.sleep(Integer.MAX_VALUE);
Telegram channel

If you still have any questions, feel free to ask me in the comments under this article or write me at promark33@gmail.com.

If I saved your day, you can support me 🤝

Leave a Reply

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