FileLockImpl.java revision d2510429e70ab91a04c67d5ca39b30f354eba221
1/* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements.  See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License.  You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.apache.harmony.nio.internal;
18
19import java.io.IOException;
20import java.nio.channels.ClosedChannelException;
21import java.nio.channels.FileChannel;
22import java.nio.channels.FileLock;
23
24/**
25 * The concrete implementation of an NIO file lock object.
26 */
27final class FileLockImpl extends FileLock {
28
29    // Remembers if this lock has been released via the API.
30    private boolean isReleased = false;
31
32    /**
33     * Answers a new file lock object with the given parameters.
34     *
35     * @param channel
36     *            the file channel hosting the lock.
37     * @param position
38     *            the start position of the lock, in bytes
39     * @param size
40     *            the length of the lock, in bytes
41     * @param shared
42     *            whether this lock is shared (true) or exclusive (false)
43     */
44    public FileLockImpl(FileChannel channel, long position, long size,
45            boolean shared) {
46        super(channel, position, size, shared);
47    }
48
49    /**
50     * Tests to see if the lock is valid. A lock can be invalidated if the
51     * channel it is acquired on is closed or if it is released. (non-Javadoc)
52     *
53     * @see java.nio.channels.FileLock#isValid()
54     */
55    @Override
56    public boolean isValid() {
57        return !isReleased && channel().isOpen();
58    }
59
60    /**
61     * Releases the file lock on the channel that acquired it. Releasing an
62     * invalid lock has no effect.
63     *
64     * @see java.nio.channels.FileLock#release()
65     */
66    @Override
67    public void release() throws IOException {
68        if (!channel().isOpen()) {
69            throw new ClosedChannelException();
70        }
71
72        if (!isReleased) {
73            ((FileChannelImpl) channel()).release(this);
74            isReleased = true;
75        }
76    }
77}
78