1/*
2 * Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team
3 *
4 * Distributable under the terms of either the Apache License (Version 2.0) or
5 * the GNU Lesser General Public License, as specified in the COPYING file.
6 *
7 * Changes are Copyright(C) 2007, 2008 by Nokia Corporation and/or its subsidiary(-ies), all rights reserved.
8*/
9#ifndef _lucene_store_Lock_
10#define _lucene_store_Lock_
11
12#if defined(_LUCENE_PRAGMA_ONCE)
13# pragma once
14#endif
15
16CL_NS_DEF(store)
17
18class LuceneLock : LUCENE_BASE
19{
20public:
21 LUCENE_STATIC_CONSTANT(int64_t, LOCK_POLL_INTERVAL = 1000);
22
23 virtual ~LuceneLock() {}
24
25 // Attempts to obtain exclusive access and immediately return upon success
26 // or failure. Return true if exclusive access is obtained.
27 virtual bool obtain() = 0;
28
29 // Attempts to obtain an exclusive lock within amount of time given.
30 // Currently polls once per second until lockWaitTimeout is passed.
31 // @param lockWaitTimeout length of time to wait in ms
32 // @return true if lock was obtained
33 // @throws IOException if lock wait times out or obtain() throws an IOException
34 bool obtain(int64_t lockWaitTimeout);
35
36 // Release exclusive access.
37 virtual void release() = 0;
38
39 // Returns true if the resource is currently locked. Note that one must
40 // still call {@link #obtain()} before using the resource.
41 virtual bool isLocked() = 0;
42
43 virtual QString toString() const = 0;
44};
45
46
47// Utility class for executing code with exclusive access.
48template<typename T>
49class LuceneLockWith
50{
51public:
52 // Constructs an executor that will grab the named lock. Defaults
53 // lockWaitTimeout to LUCENE_COMMIT_LOCK_TIMEOUT.
54 // @deprecated Kept only to avoid breaking existing code.
55 LuceneLockWith(LuceneLock* lock, int64_t lockWaitTimeout)
56 {
57 this->lock = lock;
58 this->lockWaitTimeout = lockWaitTimeout;
59 }
60
61 virtual ~LuceneLockWith() {}
62
63 // Calls {@link #doBody} while <i>lock</i> is obtained. Blocks if lock
64 // cannot be obtained immediately. Retries to obtain lock once per second
65 // until it is obtained, or until it has tried ten times. Lock is released
66 // when {@link #doBody} exits.
67 T runAndReturn()
68 {
69 bool locked = false;
70 T ret = NULL;
71 try {
72 locked = lock->obtain(lockWaitTimeout);
73 ret = doBody();
74 } _CLFINALLY (
75 if (locked)
76 lock->release();
77 );
78 return ret;
79 }
80
81 // @see runAndReturn
82 // Same as runAndReturn, except doesn't return any value. The only
83 // difference is that no void values are used
84 void run()
85 {
86 bool locked = false;
87 try {
88 locked = lock->obtain(lockWaitTimeout);
89 doBody();
90 } _CLFINALLY (
91 if (locked)
92 lock->release();
93 );
94 }
95
96protected:
97 virtual T doBody() = 0;
98
99private:
100 LuceneLock* lock;
101 int64_t lockWaitTimeout;
102};
103
104CL_NS_END
105
106#endif
107