Search code examples
javaplotjfreechartrace-condition

JFreeChart addBin with race condition?


I'm currently working on a project where I want to plot some times measured. For this I'm using JFreeChart 1.0.13.

I want to create a Histogram with SimpleHistogramBins and then add data to these bins. Here's the code:

    Double min = Collections.min(values);
    Double max = Collections.max(values);
    Double current = min;
    int range = 1000;
    double minimalOffset = 0.0000000001;
    Double stepWidth = (max-min) / range;
    SimpleHistogramDataset dataSet = new SimpleHistogramDataset("");
    for (int i = 0; i <= range; i++) {
        SimpleHistogramBin bin;
        if (i != 0) {
            bin = new SimpleHistogramBin(current + minimalOffset, current + stepWidth);
        } else {
            bin = new SimpleHistogramBin(current, current + stepWidth);
        }
        dataSet.addBin(bin);
        current += stepWidth;
    }

    for (Double value : values) {
        System.out.println(value);
        dataSet.addObservation(value);
    }  

This crashes with Exception in thread "main" java.lang.RuntimeException: No bin. At first I thought this was caused by hitting a gap in the bins, but when I started debugging, the error did not occur. The program ran through and I got a plot. Then I added this:

Thread.sleep(1000);

before

for (Double value : values) {
        System.out.println(value);
        dataSet.addObservation(value);
}  

and again, no error.

This got me thinking that maybe there is some kind of race condition? Does JFreeChart add the bins asynchronously? I would appreciate hints in any direction to why I get this kind of behaviour.

Thanks


Solution

  • If anyone should have the same problem, I found a solution:

    Instead of using SimpleHistorgramBin I'm using HistogramBin. This basically reduces my code to a few lines:

    HistogramDataset dataSet = new HistogramDataset();
    dataSet.setType(HistogramType.FREQUENCY);
    dataSet.addSeries("Hibernate", Doubles.toArray(values), 1000);
    

    This approach automatically creates the bins I need and the problem is gone.