package com.atlassian.bitbucket.util.concurrent;

import javax.annotation.Nonnull;
import java.util.concurrent.locks.Lock;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * A helper {@code AutoCloseable} to wrap a {@code Lock}, acquiring the lock during construction and releasing
 * the lock in {@link #close()}.
 */
public class LockGuard implements AutoCloseable {

    private final Lock lock;

    /**
     * Acquires the provided {@code Lock}.
     *
     * @param lock the lock to guard
     */
    public LockGuard(@Nonnull Lock lock) {
        this.lock = checkNotNull(lock, "lock");

        lock.lock();
    }

    /**
     * Releases the lock.
     */
    @Override
    public void close() {
        lock.unlock();
    }
}
