001package co.codewizards.cloudstore.core.io;
002
003import java.io.File;
004import java.io.IOException;
005import java.io.InputStream;
006import java.io.OutputStream;
007import java.util.concurrent.locks.Lock;
008
009/**
010 * Lock-file exclusively locking a certain {@link #getFile() file}.
011 * <p>
012 * An instance is acquired by invoking {@link LockFileFactory#acquire(File, long)}.
013 * <p>
014 * All methods of this interface are thread-safe.
015 * @author Marco หงุ่ยตระกูล-Schulze - marco at codewizards dot co
016 */
017public interface LockFile {
018
019        /**
020         * Gets the underlying file being locked.
021         * @return the underlying file being locked. Never <code>null</code>.
022         */
023        File getFile();
024
025        /**
026         * Releases the lock.
027         * <p>
028         * <b>Important:</b> This method <b>must</b> be called <b>exactly once</b> for every {@code LockFile} instance!
029         * It is highly recommended to use a try-finally-block:
030         * <pre>  LockFile lockFile = LockFileFactory.acquire(theFile, theTimeout);
031         *  try {
032         *    // do something
033         *  } finally {
034         *    lockFile.release();
035         *  }</pre>
036         *  <p>
037         *  This method is thread-safe and thus might be invoked on a different thread than the instance
038         *  was created. However, it must be invoked exactly once (per {@code LockFile} instance).
039         *  @see LockFileFactory#acquire(File, long)
040         *  @throws IllegalStateException if this method is invoked more than once on the same instance.
041         */
042        void release();
043
044        Lock getLock();
045
046        InputStream createInputStream() throws IOException;
047
048        OutputStream createOutputStream() throws IOException;
049
050}