01: /* Licensed to the Apache Software Foundation (ASF) under one or more
02: * contributor license agreements. See the NOTICE file distributed with
03: * this work for additional information regarding copyright ownership.
04: * The ASF licenses this file to You under the Apache License, Version 2.0
05: * (the "License"); you may not use this file except in compliance with
06: * the License. You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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:
17: package org.apache.harmony.nio.internal;
18:
19: import java.nio.channels.FileLock;
20: import java.nio.channels.OverlappingFileLockException;
21: import java.util.Comparator;
22: import java.util.Iterator;
23: import java.util.SortedSet;
24: import java.util.TreeSet;
25:
26: /**
27: * The lock manager is responsible for tracking acquired and pending locks on
28: * the underlying file channel.
29: *
30: */
31: final class LockManager {
32: // The set of acquired and pending locks.
33: private final Comparator<FileLock> lockComparator = new Comparator<FileLock>() {
34: public int compare(FileLock lock1, FileLock lock2) {
35: long position1 = lock1.position();
36: long position2 = lock2.position();
37: return position1 > position2 ? 1
38: : (position1 < position2 ? -1 : 0);
39: }
40: };
41:
42: private final SortedSet<FileLock> locks = new TreeSet<FileLock>(
43: lockComparator);
44:
45: /*
46: * Default Constructor.
47: */
48: protected LockManager() {
49: super ();
50: }
51:
52: /*
53: * Add a new pending lock to the manager. Throws an exception if the lock
54: * would overlap an existing lock. Once the lock is acquired it remains in
55: * this set as an acquired lock.
56: */
57: synchronized void addLock(FileLock lock)
58: throws OverlappingFileLockException {
59: long lockEnd = lock.position() + lock.size();
60: for (Iterator<FileLock> keyItr = locks.iterator(); keyItr
61: .hasNext();) {
62: FileLock existingLock = keyItr.next();
63: if (existingLock.position() > lockEnd) {
64: // This, and all remaining locks, start beyond our end (so
65: // cannot overlap).
66: break;
67: }
68: if (existingLock.overlaps(lock.position(), lock.size())) {
69: throw new OverlappingFileLockException();
70: }
71: }
72: locks.add(lock);
73: }
74:
75: /*
76: * Removes an acquired lock from the lock manager. If the lock did not exist
77: * in the lock manager the operation is a no-op.
78: */
79: synchronized void removeLock(FileLock lock) {
80: locks.remove(lock);
81: }
82: }
|