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