Allocator.java

/*
 * Copyright (C) 2019 uwe
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.sw4j.sample.memory.heap;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.logging.Logger;

/**
 *
 * @author Uwe Plonus &lt;u.plonus@gmail.com&gt;
 */
public class Allocator {
        //implements Runnable {

    private static final int kiByte = 1024;

    private static final Logger logger = Logger.getLogger(Allocator.class.getName());

    private byte[] data;

    private byte[] digest;

    private final Random rand = new Random();

    /**
     * Creates a new allocator and reserves {@code blocks} 1 KiB blocks.
     *
     * @param blocks the number of blocks to reserve.
     */
    public Allocator(int blocks) {
        data = new byte[blocks * kiByte];
    }

    public void calculateHash() throws NoSuchAlgorithmException {
        byte[] filler = new byte[kiByte];
        for (int i = 0; i < data.length / kiByte; i++) {
            rand.nextBytes(filler);
            System.arraycopy(filler, 0, data, kiByte * i, kiByte);
        }
        String digestAlgorithm = "SHA3-512";
        String javaVersion = System.getProperty("java.specification.version");
        try {
            double version = Double.parseDouble(javaVersion);
            if (version < 9.0d) {
                logger.config("Pre Java 9 VM detected.");
                digestAlgorithm = "SHA-512";
            } else {
                logger.config("Post Java 8 VM detected.");
            }
        } catch (NumberFormatException nfex) {
            logger.config(String.format("Unknown Java version: %s.", javaVersion));
            digestAlgorithm = "SHA-512";
        }
        logger.config(String.format("Using hash algorithm %s", digestAlgorithm));
        MessageDigest digester = MessageDigest.getInstance(digestAlgorithm);
        digest = digester.digest(data);
    }

    public String getHash() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digest.length; i++) {
            sb.append(String.format("%02x", digest[i]));
        }
        return sb.toString();
    }

//    @Override
//    public void run() {
//        data = null;
//    }

}