package edu.nyu.cs9053.concurrency.chapter14.stop;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * User: blangel
 * Date: 7/26/14
 * Time: 1:40 PM
 */
public class ThreadStopDamaged implements Runnable {

    private int alwaysEqualsB = 0;

    private int b = 0;

    @Override public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                increment();
            }
        } catch (ThreadDeath td) {
            // allow finally block to run
        } finally {
            cleanup();
        }
    }

    private synchronized void increment() {
        alwaysEqualsB += 1;
        ensureIntegrity();
        b = alwaysEqualsB;
    }

    private int ensureIntegrity() {
        int val = 0;
        int stop = (int) Math.round(Math.random() * 10);
        for (int i = 0; i < stop; i++) {
            try {
                val += 1;
                byte[] input = Integer.toBinaryString(val).getBytes();
                MessageDigest digest = MessageDigest.getInstance("MD5");
                byte[] bytes = digest.digest(input);
                val = bytes[0];
            } catch (NoSuchAlgorithmException nsae) {
                throw new RuntimeException(nsae);
            }
        }
        return val;
    }

    private void cleanup() {
        System.out.printf("cleaning up %s [ %s | %d == %d ] %n", Thread.currentThread().getName(),
                (alwaysEqualsB == b), alwaysEqualsB, b);
    }
}
