All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.carrotsearch.junitbenchmarks.AutocloseConsumer Maven / Gradle / Ivy

Go to download

A framework for writing performance micro-benchmarks using JUnit4 annotations, forked from https://github.com/carrotsearch/junit-benchmarks.

There is a newer version: 0.7.4-scijava
Show newest version
package com.carrotsearch.junitbenchmarks;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Consumers that should be closed at shutdown (if not earlier).
 */
public abstract class AutocloseConsumer implements IResultsConsumer
{
    /**
     * A list of closeables to close at shutdown (if not closed earlier).
     */
    private static List autoclose = new ArrayList();

    /**
     * A shutdown agent closing {@link #autoclose}.
     */
    private static Thread shutdownAgent;

    protected AutocloseConsumer()
    {
        initShutdownAgent();
    }

    protected static synchronized void addAutoclose(Closeable c)
    {
        autoclose.add(c);
    }

    protected static synchronized void removeAutoclose(Closeable c)
    {
        try
        {
            while (autoclose.remove(c))
            {
                // repeat.
            }
            c.close();
        }
        catch (IOException e)
        {
            // Ignore.
        }
    }

    private static synchronized void initShutdownAgent()
    {
        if (shutdownAgent == null)
        {
            shutdownAgent = new Thread()
            {
                public void run()
                {
                    for (Closeable w : new ArrayList(autoclose))
                    {
                        try
                        {
                            w.close();
                        }
                        catch (IOException e)
                        {
                            // Ignore, not much to do.
                        }
                    }
                }
            };
            Runtime.getRuntime().addShutdownHook(shutdownAgent);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy