1 /***
2 *
3 * Copyright 2003-2005 Core Developers Network Ltd.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.codehaus.wadi.core.util;
18
19 import java.util.concurrent.TimeUnit;
20 import java.util.concurrent.locks.Lock;
21
22 /***
23 * @author <a href="mailto:jules@coredevelopers.net">Jules Gosnell</a>
24 * @version $Revision$
25 */
26 public class ExtendableLease extends SimpleLease {
27
28 public interface Extender {
29 public boolean extend();
30 }
31
32 protected static final Extender _DefaultExtender = new Extender() {
33 public boolean extend() {
34 return false;
35 }
36 };
37
38 protected Extender _extender = _DefaultExtender;
39
40 protected long _leasePeriod;
41
42 public ExtendableLease(String label, Lock sync) {
43 super(label, sync);
44 }
45
46 public Handle acquire(long leasePeriod, Extender extender) throws InterruptedException {
47 Handle handle = super.acquire(leasePeriod);
48 _extender = extender;
49 return handle;
50 }
51
52 public Handle attempt(long timeframe, long leasePeriod, Extender extender) throws InterruptedException {
53 Handle handle = super.attempt(timeframe, leasePeriod);
54 _extender = extender;
55 return handle;
56 }
57
58
59 protected Handle setAlarm(long leasePeriod) {
60 _leasePeriod = leasePeriod;
61 Releaser releaser = new ExtendableReleaser();
62 _daemon.schedule(releaser, leasePeriod, TimeUnit.MILLISECONDS);
63 Handle handle = new SimpleHandle(releaser);
64 if (_lockLog.isTraceEnabled())
65 _lockLog.trace(_label + " - acquisition: " + this + "." + handle);
66 synchronized (_handles) {
67 _handles.add(handle);
68 }
69 releaser.init(handle);
70 return handle;
71 }
72
73 public class ExtendableReleaser extends Releaser {
74
75 public void run() {
76 if (_extender.extend()) {
77
78 setAlarm(_leasePeriod);
79 } else {
80
81 super.run();
82 }
83 }
84 }
85
86 }