dimanche 11 novembre 2018

Java - why is a method from a static block not getting loaded in time?

I wrote a method processMetrics that loads new metrics if the files containing the data were updated since the last request. I wanted the method to get executed every 10 seconds so decided to use ExecutorService for that purpose.

However when I'm testing a method from the class that's using the config. I can see that the method is invoked without the configuration being loaded by the executor from the static block. When I'm running the test without first calling the commented line it returns false since no config was updated. But when I run MetricsProcessor.isMetricValid("Metric_1"); and then assertTrue(MetricsProcessor.isMetricValid("Metric_1")); the config is loaded and the test returns true. What could cause such a behaviour? I came to a conclusion that it's because the MetricsProcessor class is not getting loaded in time. Is it a valid assumption?

Also, I've managed to fix the problem by explicitly calling processMetrics(); in the first line of the static block before the executor. But still not clearly understand why is this happening?

@Test
    public void testIsMetricValid() {
//        MetricsProcessor.isMetricValid("Metric_1");
        assertTrue(MetricsProcessor.isMetricValid("Metric_1"));
    }


// MetricsProcessor is a final class
private static Runnable loadMetrics = MetricsProcessor::processMetrics;
private static ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

static {
        executor.scheduleAtFixedRate(loadMetrics, 0, 10, TimeUnit.SECONDS);
    }

private static void processMetrics() {
 {
            long metricsLastMod = metricsFile.lastModified();

            if (metricsLastMod > lastMod.get()) {
                processMetricsData(metricsFile);
            lastMod.set(metricsLastMod);
            }
}

Aucun commentaire:

Enregistrer un commentaire