I've been looking into thread safety when doing multithreading. I'm looking into the use of locks to make a custom data structure threadsafe.
Is this the most suitable implementation for making this custom histogram threadsafe?
Also I'm new here. Is there a tag that I can use if I would like help tracing code to find out what it does?
Histogram class (Unsafe)
public class Histogram
{
protected long[] bins;
protected int min, max, range;
protected int numBins;
public Histogram(int max, int min, int numBins)
{
this.max = max;
this.min = min;
this.numBins = numBins;
bins = new long[numBins];
range = max - min + 1;
}
public void add(int num)
{
int bin = (int) Math.floor(((num - min) * 1.0 / range) * numBins);
bins[bin]++;
}
public int absDifference(Histogram histogram)
{
int sum = 0;
if (histogram.min == min && histogram.max == max && histogram.numBins == numBins)
for (int i = 0; i < bins.length; i++)
sum += (int) Math.abs(bins[i] - histogram.bins[i]);
return sum;
}
@Override
public String toString()
{
String out = String.format("{Min: %d, Max: %d, # Bins: %d, Values: ", min, max, numBins);
for (int i = 0; i < bins.length; i++)
out += bins[i] + ", ";
out = out.substring(0, out.length() - 2);
out += "}";
return out;
}
}
Thread safe Histogram class
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class HistogramSafe extends Histogram
{
private Lock[] binLocks;
public HistogramSafe(int max, int min, int numBins)
{
super(max, min, numBins);
binLocks = new ReentrantLock[numBins];
for (int i = 0; i < numBins; i++)
binLocks[i] = new ReentrantLock();
}
@Override
public void add(int num)
{
int bin = (int) Math.floor(((num - min) * 1.0 / range) * numBins);
binLocks[bin].lock();
bins[bin]++;
binLocks[bin].unlock();
}
}