01: /*
02: * Copyright 2004-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * 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.compass.needle.coherence;
18:
19: import java.io.IOException;
20:
21: import com.tangosol.net.NamedCache;
22: import com.tangosol.util.filter.NotFilter;
23: import com.tangosol.util.filter.PresentFilter;
24: import com.tangosol.util.processor.ConditionalPut;
25: import org.apache.commons.logging.Log;
26: import org.apache.commons.logging.LogFactory;
27: import org.apache.lucene.store.Lock;
28: import org.apache.lucene.store.LockFactory;
29:
30: /**
31: * A locak factory using Coherence invocable support in order to use the actual
32: * existance of a key within the cache to represent a lock.
33: *
34: * @author kimchy
35: */
36: public class InvocableCoherenceLockFactory extends LockFactory {
37:
38: private static final Log log = LogFactory
39: .getLog(InvocableCoherenceLockFactory.class);
40:
41: private NamedCache cache;
42:
43: private String indexName;
44:
45: public InvocableCoherenceLockFactory(NamedCache cache,
46: String indexName) {
47: this .cache = cache;
48: this .indexName = indexName;
49: }
50:
51: public void clearLock(String lockName) throws IOException {
52: cache.remove(new FileLockKey(indexName, lockName));
53: }
54:
55: public Lock makeLock(String lockName) {
56: return new CoherenceLock(lockName);
57: }
58:
59: public class CoherenceLock extends Lock {
60:
61: private FileLockKey fileLock;
62:
63: public CoherenceLock(String lockName) {
64: this .fileLock = new FileLockKey(indexName, lockName);
65: }
66:
67: public boolean isLocked() {
68: return cache.containsKey(fileLock);
69: }
70:
71: public boolean obtain() throws IOException {
72: Integer isLocked = (Integer) cache.invoke(fileLock,
73: new ConditionalPut(new NotFilter(
74: PresentFilter.INSTANCE), 1, true));
75: return isLocked == null;
76: }
77:
78: public void release() {
79: try {
80: cache.remove(fileLock);
81: } catch (Exception e) {
82: if (log.isWarnEnabled()) {
83: log.warn("Failed to release lock on index ["
84: + indexName + "]", e);
85: }
86: }
87: }
88: }
89: }
|