package org.xbib.logging.errormanager;

import java.util.logging.ErrorManager;
import org.xbib.logging.ExtErrorManager;

/**
 * An error manager which runs only once and delegates to the given error manager.
 */
public final class OnlyOnceErrorManager extends ExtErrorManager {

    private volatile ErrorManager delegate;

    /**
     * Construct a new instance.
     *
     * @param delegate the delegate error manager
     */
    public OnlyOnceErrorManager(final ErrorManager delegate) {
        this.delegate = delegate;
    }

    /**
     * Construct a new instance with a {@link SimpleErrorManager} as a delegate.
     */
    public OnlyOnceErrorManager() {
        this(new SimpleErrorManager());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void error(final String msg, final Exception ex, final int code) {
        ErrorManager delegate = this.delegate;
        if (delegate == null) {
            return;
        } else {
            synchronized (this) {
                delegate = this.delegate;
                if (delegate == null) {
                    return;
                }
                this.delegate = null;
            }
        }
        delegate.error(msg, ex, code);
    }
}
