Skip to content

Commit 8e08c13

Browse files
committed
Introduce Lock utility.
The Lock utility is an adapter for Java's Lock and ReadWrite Lock types providing an easier to consume programming model (callback-style and try-with-resources).
1 parent 8328517 commit 8e08c13

File tree

5 files changed

+389
-0
lines changed

5 files changed

+389
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* Copyright 2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
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+
package org.springframework.data.util;
17+
18+
import org.springframework.data.util.Lock.AcquiredLock;
19+
20+
/**
21+
* Default {@link Lock} implementation.
22+
*
23+
* @author Mark Paluch
24+
* @since 3.2
25+
*/
26+
class DefaultLock implements Lock, AcquiredLock {
27+
28+
private final java.util.concurrent.locks.Lock delegate;
29+
30+
DefaultLock(java.util.concurrent.locks.Lock delegate) {
31+
this.delegate = delegate;
32+
}
33+
34+
@Override
35+
public AcquiredLock lock() {
36+
delegate.lock();
37+
return this;
38+
}
39+
40+
@Override
41+
public AcquiredLock lockInterruptibly() throws InterruptedException {
42+
delegate.lockInterruptibly();
43+
return this;
44+
}
45+
46+
@Override
47+
public void close() {
48+
delegate.unlock();
49+
}
50+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
* Copyright 2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
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+
package org.springframework.data.util;
17+
18+
/**
19+
* Default holder for read and write locks.
20+
*
21+
* @author Mark Paluch
22+
* @since 3.2
23+
*/
24+
record DefaultReadWriteLock(Lock readLock, Lock writeLock) implements ReadWriteLock {
25+
26+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
/*
2+
* Copyright 2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
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+
package org.springframework.data.util;
17+
18+
import java.util.function.Supplier;
19+
20+
import org.springframework.util.Assert;
21+
22+
/**
23+
* {@code Lock} provides more extensive locking operations than can be obtained using {@code synchronized} methods and
24+
* {@link java.util.concurrent.locks.Lock}. It allows more flexible structuring and an improved usage model.
25+
* <p>
26+
* This Lock abstraction is an extension to the {@link java.util.concurrent.locks.Lock lock utilities} and intended for
27+
* easier functional and try-with-resources usage.
28+
*
29+
* <pre class="code">
30+
* ReentrantLock backend = new ReentrantLock();
31+
*
32+
* Lock lock = Lock.of(backend);
33+
*
34+
* lock.executeWithoutResult(() -> {
35+
* // callback without returning a result
36+
* });
37+
*
38+
* lock.execute(() -> {
39+
* // callback returning a result
40+
* return …;
41+
* });
42+
* </pre>
43+
*
44+
* @author Mark Paluch
45+
* @since 3.2
46+
*/
47+
public interface Lock {
48+
49+
/**
50+
* Create a new {@link Lock} adapter for the given {@link java.util.concurrent.locks.Lock delegate}.
51+
*
52+
* @param delegate must not be {@literal null}.
53+
* @return a new {@link Lock} adapter.
54+
*/
55+
static Lock of(java.util.concurrent.locks.Lock delegate) {
56+
57+
Assert.notNull(delegate, "Lock delegate must not be null");
58+
59+
return new DefaultLock(delegate);
60+
}
61+
62+
/**
63+
* Acquires the lock.
64+
* <p>
65+
* If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies
66+
* dormant until the lock has been acquired.
67+
*
68+
* @see java.util.concurrent.locks.Lock#lock()
69+
*/
70+
AcquiredLock lock();
71+
72+
/**
73+
* Acquires the lock unless the current thread is {@linkplain Thread#interrupt interrupted}.
74+
* <p>
75+
* Acquires the lock if it is available and returns immediately.
76+
* <p>
77+
* If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies
78+
* dormant until one of two things happens:
79+
* <ul>
80+
* <li>The lock is acquired by the current thread; or
81+
* <li>Some other thread {@linkplain Thread#interrupt interrupts} the current thread, and interruption of lock
82+
* acquisition is supported.
83+
* </ul>
84+
* <p>
85+
* If the current thread:
86+
* <ul>
87+
* <li>has its interrupted status set on entry to this method; or
88+
* <li>is {@linkplain Thread#interrupt interrupted} while acquiring the lock, and interruption of lock acquisition is
89+
* supported,
90+
* </ul>
91+
* then {@link InterruptedException} is thrown and the current thread's interrupted status is cleared.
92+
*/
93+
AcquiredLock lockInterruptibly() throws InterruptedException;
94+
95+
/**
96+
* Execute the action specified by the given callback object guarded by a lock and return its result. The
97+
* {@code action} is only executed once the lock has been acquired.
98+
*
99+
* @param action the action to run.
100+
* @return the result of the action.
101+
* @param <T> type of the result.
102+
* @throws RuntimeException if thrown by the action
103+
*/
104+
default <T> T execute(Supplier<T> action) {
105+
try (AcquiredLock l = lock()) {
106+
return action.get();
107+
}
108+
}
109+
110+
/**
111+
* Execute the action specified by the given callback object guarded by a lock. The {@code action} is only executed
112+
* once the lock has been acquired.
113+
*
114+
* @param action the action to run.
115+
* @throws RuntimeException if thrown by the action.
116+
*/
117+
default void executeWithoutResult(Runnable action) {
118+
try (AcquiredLock l = lock()) {
119+
action.run();
120+
}
121+
}
122+
123+
/**
124+
* An acquired lock can be used with try-with-resources for easier releasing.
125+
*/
126+
interface AcquiredLock extends AutoCloseable {
127+
128+
/**
129+
* Releases the lock.
130+
*
131+
* @see java.util.concurrent.locks.Lock#unlock()
132+
*/
133+
@Override
134+
void close();
135+
}
136+
137+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* Copyright 2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
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+
package org.springframework.data.util;
17+
18+
import org.springframework.util.Assert;
19+
20+
/**
21+
* A {@code ReadWriteLock} maintains a pair of associated {@link Lock locks}, one for read-only operations and one for
22+
* writing. The {@link #readLock read lock} may be held simultaneously by multiple reader threads, so long as there are
23+
* no writers. The {@link #writeLock write lock} is exclusive.
24+
*
25+
* @author Mark Paluch
26+
* @since 3.2
27+
* @see Lock
28+
*/
29+
public interface ReadWriteLock {
30+
31+
/**
32+
* Create a new {@link ReadWriteLock} adapter for the given {@link java.util.concurrent.locks.ReadWriteLock delegate}.
33+
*
34+
* @param delegate must not be {@literal null}.
35+
* @return a new {@link ReadWriteLock} adapter.
36+
*/
37+
static ReadWriteLock of(java.util.concurrent.locks.ReadWriteLock delegate) {
38+
39+
Assert.notNull(delegate, "Lock delegate must not be null");
40+
41+
return new DefaultReadWriteLock(Lock.of(delegate.readLock()), Lock.of(delegate.writeLock()));
42+
}
43+
44+
/**
45+
* Returns the lock used for reading.
46+
*
47+
* @return the lock used for reading
48+
* @see java.util.concurrent.locks.ReadWriteLock#readLock()
49+
*/
50+
Lock readLock();
51+
52+
/**
53+
* Returns the lock used for reading.
54+
*
55+
* @return the lock used for writing.
56+
* @see java.util.concurrent.locks.ReadWriteLock#writeLock() ()
57+
*/
58+
Lock writeLock();
59+
60+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
/*
2+
* Copyright 2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
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+
package org.springframework.data.util;
17+
18+
import static org.assertj.core.api.Assertions.*;
19+
20+
import java.util.concurrent.locks.ReentrantLock;
21+
import java.util.concurrent.locks.ReentrantReadWriteLock;
22+
23+
import org.junit.jupiter.api.Test;
24+
import org.springframework.data.util.Lock.AcquiredLock;
25+
26+
/**
27+
* Unit tests for {@link Lock}.
28+
*
29+
* @author Mark Paluch
30+
*/
31+
class LockUnitTests {
32+
33+
@Test
34+
void shouldDelegateLock() {
35+
36+
ReentrantLock backend = new ReentrantLock();
37+
38+
Lock lock = Lock.of(backend);
39+
40+
lock.executeWithoutResult(() -> {
41+
42+
assertThat(backend.isLocked()).isTrue();
43+
assertThat(backend.isHeldByCurrentThread()).isTrue();
44+
});
45+
46+
lock.execute(() -> {
47+
48+
assertThat(backend.isLocked()).isTrue();
49+
assertThat(backend.isHeldByCurrentThread()).isTrue();
50+
return null;
51+
});
52+
53+
assertThat(backend.isLocked()).isFalse();
54+
}
55+
56+
@Test
57+
void shouldDelegateReadWriteLock() {
58+
59+
ReentrantReadWriteLock backend = new ReentrantReadWriteLock();
60+
61+
ReadWriteLock lock = ReadWriteLock.of(backend);
62+
63+
lock.readLock().executeWithoutResult(() -> {
64+
assertThat(backend.getReadLockCount()).isEqualTo(1);
65+
});
66+
67+
lock.writeLock().executeWithoutResult(() -> {
68+
assertThat(backend.isWriteLocked()).isTrue();
69+
});
70+
71+
assertThat(backend.getReadLockCount()).isEqualTo(0);
72+
assertThat(backend.isWriteLocked()).isFalse();
73+
}
74+
75+
@Test
76+
void lockTryWithResources() {
77+
78+
ReentrantLock backend = new ReentrantLock();
79+
Lock lock = Lock.of(backend);
80+
81+
try (AcquiredLock l = lock.lock()) {
82+
assertThat(backend.isLocked()).isTrue();
83+
assertThat(backend.isHeldByCurrentThread()).isTrue();
84+
}
85+
86+
assertThat(backend.isLocked()).isFalse();
87+
}
88+
89+
@Test
90+
void lockInterruptiblyTryWithResources() {
91+
92+
ReentrantLock backend = new ReentrantLock();
93+
Lock lock = Lock.of(backend);
94+
95+
try (AcquiredLock l = lock.lockInterruptibly()) {
96+
assertThat(backend.isLocked()).isTrue();
97+
assertThat(backend.isHeldByCurrentThread()).isTrue();
98+
} catch (InterruptedException e) {
99+
throw new RuntimeException(e);
100+
}
101+
102+
assertThat(backend.isLocked()).isFalse();
103+
}
104+
105+
@Test
106+
void shouldReturnResult() {
107+
108+
ReentrantLock backend = new ReentrantLock();
109+
110+
Lock lock = Lock.of(backend);
111+
112+
String result = lock.execute(() -> "foo");
113+
114+
assertThat(result).isEqualTo("foo");
115+
}
116+
}

0 commit comments

Comments
 (0)