1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 package org.spf4j.concurrent.jdbc;
33
34 import java.sql.SQLException;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.TimeoutException;
37 import java.util.concurrent.locks.Condition;
38 import java.util.concurrent.locks.Lock;
39 import javax.sql.DataSource;
40 import org.spf4j.base.ExecutionContexts;
41 import org.spf4j.base.UncheckedTimeoutException;
42 import org.spf4j.concurrent.LockRuntimeException;
43
44
45
46
47
48 public final class JdbcLock implements Lock, AutoCloseable {
49
50 private final JdbcSemaphore semaphore;
51
52 private final int jdbcTimeoutSeconds;
53
54 public JdbcLock(final DataSource dataSource, final SemaphoreTablesDesc semTableDesc,
55 final String lockName, final int jdbcTimeoutSeconds) throws InterruptedException, SQLException {
56 this.semaphore = new JdbcSemaphore(dataSource, semTableDesc, lockName, 1, jdbcTimeoutSeconds, true);
57 this.jdbcTimeoutSeconds = jdbcTimeoutSeconds;
58 this.semaphore.registerJmx();
59 }
60
61 @Override
62 public void lock() {
63 try {
64 semaphore.acquire(ExecutionContexts.getMillisToDeadline(), TimeUnit.MILLISECONDS);
65 } catch (InterruptedException ex) {
66 Thread.currentThread().interrupt();
67 throw new LockRuntimeException(ex);
68 } catch (TimeoutException ex) {
69 throw new UncheckedTimeoutException(ex);
70 }
71 }
72
73 @Override
74 public void lockInterruptibly() throws InterruptedException {
75 try {
76 semaphore.acquire(ExecutionContexts.getMillisToDeadline(), TimeUnit.MILLISECONDS);
77 } catch (TimeoutException ex) {
78 throw new UncheckedTimeoutException(ex);
79 }
80 }
81
82 @Override
83 public boolean tryLock() {
84 try {
85 return semaphore.tryAcquire(((long) jdbcTimeoutSeconds) * 2, TimeUnit.SECONDS);
86 } catch (InterruptedException ex) {
87 Thread.currentThread().interrupt();
88 throw new LockRuntimeException(ex);
89 }
90 }
91
92 @Override
93 public boolean tryLock(final long time, final TimeUnit unit) throws InterruptedException {
94 return semaphore.tryAcquire(time, unit);
95 }
96
97 @Override
98 public void unlock() {
99 semaphore.release();
100 }
101
102 @Override
103 public Condition newCondition() {
104 throw new UnsupportedOperationException();
105 }
106
107 @Override
108 public void close() {
109 semaphore.close();
110 }
111
112 @Override
113 public String toString() {
114 return "JdbcLock{" + "semaphore=" + semaphore + ", jdbcTimeoutSeconds=" + jdbcTimeoutSeconds + '}';
115 }
116
117
118
119 }