pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / src / java / org / apache / lucene / store / SingleInstanceLockFactory.java
1 package org.apache.lucene.store;
2
3 /**
4  * Licensed to the Apache Software Foundation (ASF) under one or more
5  * contributor license agreements.  See the NOTICE file distributed with
6  * this work for additional information regarding copyright ownership.
7  * The ASF licenses this file to You under the Apache License, Version 2.0
8  * (the "License"); you may not use this file except in compliance with
9  * the License.  You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 import java.io.IOException;
21 import java.util.HashSet;
22
23 /**
24  * Implements {@link LockFactory} for a single in-process instance,
25  * meaning all locking will take place through this one instance.
26  * Only use this {@link LockFactory} when you are certain all
27  * IndexReaders and IndexWriters for a given index are running
28  * against a single shared in-process Directory instance.  This is
29  * currently the default locking for RAMDirectory.
30  *
31  * @see LockFactory
32  */
33
34 public class SingleInstanceLockFactory extends LockFactory {
35
36   private HashSet<String> locks = new HashSet<String>();
37
38   @Override
39   public Lock makeLock(String lockName) {
40     // We do not use the LockPrefix at all, because the private
41     // HashSet instance effectively scopes the locking to this
42     // single Directory instance.
43     return new SingleInstanceLock(locks, lockName);
44   }
45
46   @Override
47   public void clearLock(String lockName) throws IOException {
48     synchronized(locks) {
49       if (locks.contains(lockName)) {
50         locks.remove(lockName);
51       }
52     }
53   }
54 }
55
56 class SingleInstanceLock extends Lock {
57
58   String lockName;
59   private HashSet<String> locks;
60
61   public SingleInstanceLock(HashSet<String> locks, String lockName) {
62     this.locks = locks;
63     this.lockName = lockName;
64   }
65
66   @Override
67   public boolean obtain() throws IOException {
68     synchronized(locks) {
69       return locks.add(lockName);
70     }
71   }
72
73   @Override
74   public void release() {
75     synchronized(locks) {
76       locks.remove(lockName);
77     }
78   }
79
80   @Override
81   public boolean isLocked() {
82     synchronized(locks) {
83       return locks.contains(lockName);
84     }
85   }
86
87   @Override
88   public String toString() {
89     return super.toString() + ": " + lockName;
90   }
91 }