1 /*
   2  * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.nio.channels;
  27 
  28 import java.io.IOException;
  29 import java.util.Objects;
  30 
  31 /**
  32  * A token representing a lock on a region of a file.
  33  *
  34  * <p> A file-lock object is created each time a lock is acquired on a file via
  35  * one of the {@link FileChannel#lock(long,long,boolean) lock} or {@link
  36  * FileChannel#tryLock(long,long,boolean) tryLock} methods of the
  37  * {@link FileChannel} class, or the {@link
  38  * AsynchronousFileChannel#lock(long,long,boolean,Object,CompletionHandler) lock}
  39  * or {@link AsynchronousFileChannel#tryLock(long,long,boolean) tryLock}
  40  * methods of the {@link AsynchronousFileChannel} class.
  41  *
  42  * <p> A file-lock object is initially valid.  It remains valid until the lock
  43  * is released by invoking the {@link #release release} method, by closing the
  44  * channel that was used to acquire it, or by the termination of the Java
  45  * virtual machine, whichever comes first.  The validity of a lock may be
  46  * tested by invoking its {@link #isValid isValid} method.
  47  *
  48  * <p> A file lock is either <i>exclusive</i> or <i>shared</i>.  A shared lock
  49  * prevents other concurrently-running programs from acquiring an overlapping
  50  * exclusive lock, but does allow them to acquire overlapping shared locks.  An
  51  * exclusive lock prevents other programs from acquiring an overlapping lock of
  52  * either type.  Once it is released, a lock has no further effect on the locks
  53  * that may be acquired by other programs.
  54  *
  55  * <p> Whether a lock is exclusive or shared may be determined by invoking its
  56  * {@link #isShared isShared} method.  Some platforms do not support shared
  57  * locks, in which case a request for a shared lock is automatically converted
  58  * into a request for an exclusive lock.
  59  *
  60  * <p> The locks held on a particular file by a single Java virtual machine do
  61  * not overlap.  The {@link #overlaps overlaps} method may be used to test
  62  * whether a candidate lock range overlaps an existing lock.
  63  *
  64  * <p> A file-lock object records the file channel upon whose file the lock is
  65  * held, the type and validity of the lock, and the position and size of the
  66  * locked region.  Only the validity of a lock is subject to change over time;
  67  * all other aspects of a lock's state are immutable.
  68  *
  69  * <p> File locks are held on behalf of the entire Java virtual machine.
  70  * They are not suitable for controlling access to a file by multiple
  71  * threads within the same virtual machine.
  72  *
  73  * <p> File-lock objects are safe for use by multiple concurrent threads.
  74  *
  75  *
  76  * <a name="pdep"></a><h2> Platform dependencies </h2>
  77  *
  78  * <p> This file-locking API is intended to map directly to the native locking
  79  * facility of the underlying operating system.  Thus the locks held on a file
  80  * should be visible to all programs that have access to the file, regardless
  81  * of the language in which those programs are written.
  82  *
  83  * <p> Whether or not a lock actually prevents another program from accessing
  84  * the content of the locked region is system-dependent and therefore
  85  * unspecified.  The native file-locking facilities of some systems are merely
  86  * <i>advisory</i>, meaning that programs must cooperatively observe a known
  87  * locking protocol in order to guarantee data integrity.  On other systems
  88  * native file locks are <i>mandatory</i>, meaning that if one program locks a
  89  * region of a file then other programs are actually prevented from accessing
  90  * that region in a way that would violate the lock.  On yet other systems,
  91  * whether native file locks are advisory or mandatory is configurable on a
  92  * per-file basis.  To ensure consistent and correct behavior across platforms,
  93  * it is strongly recommended that the locks provided by this API be used as if
  94  * they were advisory locks.
  95  *
  96  * <p> On some systems, acquiring a mandatory lock on a region of a file
  97  * prevents that region from being {@link java.nio.channels.FileChannel#map
  98  * <i>mapped into memory</i>}, and vice versa.  Programs that combine
  99  * locking and mapping should be prepared for this combination to fail.
 100  *
 101  * <p> On some systems, closing a channel releases all locks held by the Java
 102  * virtual machine on the underlying file regardless of whether the locks were
 103  * acquired via that channel or via another channel open on the same file.  It
 104  * is strongly recommended that, within a program, a unique channel be used to
 105  * acquire all locks on any given file.
 106  *
 107  * <p> Some network filesystems permit file locking to be used with
 108  * memory-mapped files only when the locked regions are page-aligned and a
 109  * whole multiple of the underlying hardware's page size.  Some network
 110  * filesystems do not implement file locks on regions that extend past a
 111  * certain position, often 2<sup>30</sup> or 2<sup>31</sup>.  In general, great
 112  * care should be taken when locking files that reside on network filesystems.
 113  *
 114  *
 115  * @author Mark Reinhold
 116  * @author JSR-51 Expert Group
 117  * @since 1.4
 118  */
 119 
 120 public abstract class FileLock implements AutoCloseable {
 121 
 122     private final Channel channel;
 123     private final long position;
 124     private final long size;
 125     private final boolean shared;
 126 
 127     /**
 128      * Initializes a new instance of this class.
 129      *
 130      * @param  channel
 131      *         The file channel upon whose file this lock is held; must be
 132      *         non-{@code null}
 133      *
 134      * @param  position
 135      *         The position within the file at which the locked region starts;
 136      *         must be non-negative
 137      *
 138      * @param  size
 139      *         The size of the locked region; must be non-negative, and the sum
 140      *         <tt>position</tt>&nbsp;+&nbsp;<tt>size</tt> must be non-negative
 141      *
 142      * @param  shared
 143      *         <tt>true</tt> if this lock is shared,
 144      *         <tt>false</tt> if it is exclusive
 145      *
 146      * @throws IllegalArgumentException
 147      *         If the preconditions on the parameters do not hold
 148      */
 149     protected FileLock(FileChannel channel,
 150                        long position, long size, boolean shared)
 151     {
 152         Objects.requireNonNull(channel, "Null channel");
 153         if (position < 0)
 154             throw new IllegalArgumentException("Negative position");
 155         if (size < 0)
 156             throw new IllegalArgumentException("Negative size");
 157         if (position + size < 0)
 158             throw new IllegalArgumentException("Negative position + size");
 159         this.channel = channel;
 160         this.position = position;
 161         this.size = size;
 162         this.shared = shared;
 163     }
 164 
 165     /**
 166      * Initializes a new instance of this class.
 167      *
 168      * @param  channel
 169      *         The channel upon whose file this lock is held; must be
 170      *         non-{@code null}
 171      *
 172      * @param  position
 173      *         The position within the file at which the locked region starts;
 174      *         must be non-negative
 175      *
 176      * @param  size
 177      *         The size of the locked region; must be non-negative, and the sum
 178      *         <tt>position</tt>&nbsp;+&nbsp;<tt>size</tt> must be non-negative
 179      *
 180      * @param  shared
 181      *         <tt>true</tt> if this lock is shared,
 182      *         <tt>false</tt> if it is exclusive
 183      *
 184      * @throws IllegalArgumentException
 185      *         If the preconditions on the parameters do not hold
 186      *
 187      * @since 1.7
 188      */
 189     protected FileLock(AsynchronousFileChannel channel,
 190                        long position, long size, boolean shared)
 191     {
 192         Objects.requireNonNull(channel, "Null channel");
 193         if (position < 0)
 194             throw new IllegalArgumentException("Negative position");
 195         if (size < 0)
 196             throw new IllegalArgumentException("Negative size");
 197         if (position + size < 0)
 198             throw new IllegalArgumentException("Negative position + size");
 199         this.channel = channel;
 200         this.position = position;
 201         this.size = size;
 202         this.shared = shared;
 203     }
 204 
 205     /**
 206      * Returns the file channel upon whose file this lock was acquired.
 207      *
 208      * <p> This method has been superseded by the {@link #acquiredBy acquiredBy}
 209      * method.
 210      *
 211      * @return  The file channel, or {@code null} if the file lock was not
 212      *          acquired by a file channel.
 213      */
 214     public final FileChannel channel() {
 215         return (channel instanceof FileChannel) ? (FileChannel)channel : null;
 216     }
 217 
 218     /**
 219      * Returns the channel upon whose file this lock was acquired.
 220      *
 221      * @return  The channel upon whose file this lock was acquired.
 222      *
 223      * @since 1.7
 224      */
 225     public Channel acquiredBy() {
 226         return channel;
 227     }
 228 
 229     /**
 230      * Returns the position within the file of the first byte of the locked
 231      * region.
 232      *
 233      * <p> A locked region need not be contained within, or even overlap, the
 234      * actual underlying file, so the value returned by this method may exceed
 235      * the file's current size.  </p>
 236      *
 237      * @return  The position
 238      */
 239     public final long position() {
 240         return position;
 241     }
 242 
 243     /**
 244      * Returns the size of the locked region in bytes.
 245      *
 246      * <p> A locked region need not be contained within, or even overlap, the
 247      * actual underlying file, so the value returned by this method may exceed
 248      * the file's current size.  </p>
 249      *
 250      * @return  The size of the locked region
 251      */
 252     public final long size() {
 253         return size;
 254     }
 255 
 256     /**
 257      * Tells whether this lock is shared.
 258      *
 259      * @return <tt>true</tt> if lock is shared,
 260      *         <tt>false</tt> if it is exclusive
 261      */
 262     public final boolean isShared() {
 263         return shared;
 264     }
 265 
 266     /**
 267      * Tells whether or not this lock overlaps the given lock range.
 268      *
 269      * @param   position
 270      *          The starting position of the lock range
 271      * @param   size
 272      *          The size of the lock range
 273      *
 274      * @return  <tt>true</tt> if, and only if, this lock and the given lock
 275      *          range overlap by at least one byte
 276      */
 277     public final boolean overlaps(long position, long size) {
 278         if (position + size <= this.position)
 279             return false;               // That is below this
 280         if (this.position + this.size <= position)
 281             return false;               // This is below that
 282         return true;
 283     }
 284 
 285     /**
 286      * Tells whether or not this lock is valid.
 287      *
 288      * <p> A lock object remains valid until it is released or the associated
 289      * file channel is closed, whichever comes first.  </p>
 290      *
 291      * @return  <tt>true</tt> if, and only if, this lock is valid
 292      */
 293     public abstract boolean isValid();
 294 
 295     /**
 296      * Releases this lock.
 297      *
 298      * <p> If this lock object is valid then invoking this method releases the
 299      * lock and renders the object invalid.  If this lock object is invalid
 300      * then invoking this method has no effect.  </p>
 301      *
 302      * @throws  ClosedChannelException
 303      *          If the channel that was used to acquire this lock
 304      *          is no longer open
 305      *
 306      * @throws  IOException
 307      *          If an I/O error occurs
 308      */
 309     public abstract void release() throws IOException;
 310 
 311     /**
 312      * This method invokes the {@link #release} method. It was added
 313      * to the class so that it could be used in conjunction with the
 314      * automatic resource management block construct.
 315      *
 316      * @since 1.7
 317      */
 318     public final void close() throws IOException {
 319         release();
 320     }
 321 
 322     /**
 323      * Returns a string describing the range, type, and validity of this lock.
 324      *
 325      * @return  A descriptive string
 326      */
 327     public final String toString() {
 328         return (this.getClass().getName()
 329                 + "[" + position
 330                 + ":" + size
 331                 + " " + (shared ? "shared" : "exclusive")
 332                 + " " + (isValid() ? "valid" : "invalid")
 333                 + "]");
 334     }
 335 
 336 }