├── .gitignore
├── .travis.yml
├── README.md
├── doc
├── lock-chart.ai
├── lock-chart.png
├── lock-chart.svg
└── release.md
├── license.txt
├── pom.xml
└── src
├── main
└── java
│ └── de
│ └── jkeylockmanager
│ ├── contract
│ ├── Contract.java
│ └── ContractBrokenError.java
│ └── manager
│ ├── KeyLockManager.java
│ ├── KeyLockManagers.java
│ ├── LockCallback.java
│ ├── ReturnValueLockCallback.java
│ ├── exception
│ ├── KeyLockManagerException.java
│ ├── KeyLockManagerInterruptedException.java
│ └── KeyLockManagerTimeoutException.java
│ └── implementation
│ └── lockstripe
│ ├── CountingLock.java
│ └── StripedKeyLockManager.java
├── test
└── java
│ └── de
│ └── jkeylockmanager
│ ├── contract
│ └── ContractTest.java
│ └── manager
│ └── implementation
│ └── lockstripe
│ └── StripedKeyLockManagerTest.java
└── testslow
└── java
└── de
└── jkeylockmanager
└── manager
└── implementation
└── lockstripe
└── StripedKeyLockManagerStressTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | target
2 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | jdk:
3 | - oraclejdk8
4 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | JKeyLockManager
2 | ===============
3 |
4 |
5 | JKeyLockManager (KLM) provides fine-grained locking with application specific keys. All resource and exception handling for the active set of keys is encapsulated in the manager. Thereby it is easier to follow the recommendation of Robert C. Martin: **"Keep your concurrency-related code separate from other code."**
6 |
7 | ### Abstract
8 |
9 | The KLM offers the possibility of performing callbacks within a lock. It selects the lock on the basis of a given key.
10 | ```
11 | manager.executeLocked("test1", () -> { // run block in lock });
12 | ```
13 | The KLM takes over the maintenance of the locks and keys completely. It can manage arbitrary quantities of keys and locks. One lock is assigned to each key and the necessary locks are produced automatically. The KLM ensures that unneeded keys and locks are being released quickly.
14 |
15 | ### Behavior with concurrency
16 |
17 |
18 |
19 | If a thread executes a callback with a key **A**, a second thread can execute a callback with a key **B concurrently**. Another thread, which is trying to execute a callback with a key **A**, has to wait until the first thread leaves the callback.
20 |
21 | The methods of the KLM are reentrant and interruptible.
22 |
23 | ### Example - web service with concurrency constraint
24 |
25 | A local system exports weather data to a distributed web service. The service is called for a large set of cities and every service access for a city has a high response time. Since the service is made available on a cluster, the import can be strongly accelerated by concurrent access. The service forbids concurrent access to the weather data of the **same** city. A simple lock is used in order to ensure compliance with this constraint.
26 |
27 | #### A simple solution with a global lock
28 |
29 | ```java
30 | public class WeatherServiceProxy {
31 | public synchronized void updateWeatherData(String cityName, float temperature) {
32 | delegate.updateWeatherData(cityName, temperature);
33 | }
34 | }
35 | ```
36 |
37 | #### Solution with KLM
38 |
39 | ```java
40 | public class WeatherServiceProxy {
41 | private final KeyLockManager lockManager = KeyLockManagers.newManager();
42 |
43 | public void updateWeatherData(String cityName, float temperature) {
44 | lockManager.executeLocked(cityName, () -> delegate.updateWeatherData(cityName, temperature));
45 | }
46 | ```
47 | Now threads that work on weather data from different cities can enter the locked section concurrently. Compliance with the constraint **and** speedup has been achieved.
48 |
49 | ### Getting started
50 |
51 | #### Maven
52 |
53 | Java 8
54 |
55 | ```
56 |
57 | de.jkeylockmanager
58 | jkeylockmanager
59 | 2.1.0
60 |
61 | ```
62 |
63 | Java 5, 6, 7
64 | ```
65 |
66 | de.jkeylockmanager
67 | jkeylockmanager
68 | 1.2.0
69 |
70 | ```
71 |
72 |
73 | #### Source
74 |
75 | Start with `KeyLockManagers` in order to get instances of KLM.
76 |
77 |
78 |
79 | ### Versions
80 |
81 |
82 | #### Version 2
83 |
84 | ##### 2.1.0
85 |
86 | Make number of stripes configurable (Based on pull request from https://github.com/jschmied)
87 |
88 | ###### Example
89 | ```java
90 | KeyLockManager lockManager = new StripedKeyLockManager(10, TimeUnit.MINUTES, 120);
91 | ```
92 |
93 | ##### 2.0.0
94 |
95 | Use of Java 8
96 |
97 |
98 | #### Version 1
99 |
100 | ##### Version 1.2.0
101 |
102 | Backport from Version 2 - Make number of stripes configurable
103 |
104 | ##### Version 1.1.0
105 |
106 | Simplified exception handling.
107 |
108 | Execution exceptions inside of callbacks are no longer wrapped. Callbacks now have to wrap checked exceptions in unchecked exceptions.
109 |
110 | ##### Version 1.0.1
111 |
112 | Transition to maven central
113 |
114 |
115 |
116 | ### Build state
117 |
118 | #### master
119 | [](https://travis-ci.org/mojgh/JKeyLockManager)
120 |
121 | #### version-1
122 | [](https://travis-ci.org/mojgh/JKeyLockManager)
123 |
124 |
--------------------------------------------------------------------------------
/doc/lock-chart.ai:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mojgh/JKeyLockManager/7b69d27f3cde0224a599d6a43ea9d4f1d016d5f1/doc/lock-chart.ai
--------------------------------------------------------------------------------
/doc/lock-chart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mojgh/JKeyLockManager/7b69d27f3cde0224a599d6a43ea9d4f1d016d5f1/doc/lock-chart.png
--------------------------------------------------------------------------------
/doc/lock-chart.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/doc/release.md:
--------------------------------------------------------------------------------
1 | # Deploy
2 |
3 | ## Prepare
4 | set version in pom.xml
5 | commit and tag
6 |
7 | ## Deploy to sonatype nexus
8 | mvn -P release clean deploy
9 |
10 |
11 | ## check
12 |
13 | ### check sonatype nexus (staging is not active - releases are deployed directly)
14 | https://oss.sonatype.org
15 |
16 | ### check central (~ 10 min later)
17 | http://repo1.maven.org/maven2/de/jkeylockmanager/jkeylockmanager/
18 |
19 |
20 |
21 | # Documentation
22 | http://central.sonatype.org/pages/ossrh-guide.html
23 | http://central.sonatype.org/pages/apache-maven.html
24 |
25 |
--------------------------------------------------------------------------------
/license.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 | 4.0.0
5 |
6 | de.jkeylockmanager
7 | jkeylockmanager
8 | jar
9 | 2.1.0
10 |
11 | JKeyLockManager
12 | http://www.jkeylockmanager.de
13 | JKeyLockManager allows fine-grained locking with application specific keys.
14 |
15 |
16 | UTF-8
17 |
18 |
19 |
20 |
21 | junit
22 | junit
23 | 4.11
24 | test
25 |
26 |
27 | org.hamcrest
28 | hamcrest-all
29 | 1.3
30 | test
31 |
32 |
33 |
34 |
35 |
36 |
37 | org.apache.maven.plugins
38 | maven-compiler-plugin
39 | 3.1
40 |
41 | 1.8
42 | 1.8
43 |
44 |
45 |
46 | org.codehaus.mojo
47 | build-helper-maven-plugin
48 | 1.9.1
49 |
50 |
51 | add-test-source
52 | generate-sources
53 |
54 | add-test-source
55 |
56 |
57 |
58 | src/testslow/java
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | ossrh
70 | https://oss.sonatype.org/content/repositories/snapshots
71 |
72 |
73 |
74 |
75 |
76 |
77 | release
78 |
79 |
80 |
81 | org.apache.maven.plugins
82 | maven-source-plugin
83 | 2.4
84 |
85 |
86 | attach-sources
87 |
88 | jar-no-fork
89 |
90 |
91 |
92 |
93 |
94 | org.apache.maven.plugins
95 | maven-javadoc-plugin
96 | 2.10.1
97 |
98 |
99 | attach-javadocs
100 |
101 | jar
102 |
103 |
104 |
105 |
106 |
107 | org.apache.maven.plugins
108 | maven-gpg-plugin
109 | 1.5
110 |
111 |
112 | sign-artifacts
113 | verify
114 |
115 | sign
116 |
117 |
118 |
119 |
120 |
121 | org.sonatype.plugins
122 | nexus-staging-maven-plugin
123 | 1.6.5
124 | true
125 |
126 | ossrh
127 | https://oss.sonatype.org/
128 | true
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 | scm:git:https://github.com/mojgh/JKeyLockManager.git
138 | scm:git:https://github.com/mojgh/JKeyLockManager.git
139 | https://github.com/mojgh/JKeyLockManager.git
140 |
141 |
142 |
143 |
144 | Marc-Olaf Jaschke
145 | mojaschke@googlemail.com
146 | http://www.jkeylockmanager.de
147 |
148 |
149 |
150 |
151 |
152 | The Apache Software License, Version 2.0
153 | http://www.apache.org/licenses/LICENSE-2.0
154 |
155 |
156 |
157 |
--------------------------------------------------------------------------------
/src/main/java/de/jkeylockmanager/contract/Contract.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Marc-Olaf Jaschke
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 | * http://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 |
17 | package de.jkeylockmanager.contract;
18 |
19 | /**
20 | *
21 | * @author Marc-Olaf Jaschke
22 | *
23 | */
24 | public final class Contract {
25 |
26 | public static void isNotNull(final Object object, final String textualCondition) {
27 | isTrue(object != null, textualCondition);
28 | }
29 |
30 | public static void isTrue(final boolean condition, final String textualCondition) {
31 | if (!condition) {
32 | throw new ContractBrokenError(textualCondition == null ? "" : textualCondition);
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/de/jkeylockmanager/contract/ContractBrokenError.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Marc-Olaf Jaschke
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 | * http://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 |
17 | package de.jkeylockmanager.contract;
18 |
19 | /**
20 | *
21 | * @author Marc-Olaf Jaschke
22 | *
23 | */
24 | class ContractBrokenError extends Error {
25 |
26 | private static final long serialVersionUID = -5111361891728626973L;
27 |
28 | ContractBrokenError(final String textualCondition) {
29 | super(String.format("contract broken: %s", textualCondition));
30 | }
31 |
32 | }
--------------------------------------------------------------------------------
/src/main/java/de/jkeylockmanager/manager/KeyLockManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Marc-Olaf Jaschke
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 | * http://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 |
17 | package de.jkeylockmanager.manager;
18 |
19 | import de.jkeylockmanager.manager.exception.KeyLockManagerInterruptedException;
20 | import de.jkeylockmanager.manager.exception.KeyLockManagerTimeoutException;
21 |
22 | /**
23 | * Protect a unit of work from concurrent access based on a key. Only one thread
24 | * can enter the locked unit of work for a given key. Other threads that work on
25 | * the same key concurrently have to wait until the first thread leaves the
26 | * locked unit.
27 | *
28 | * All implementations have to be reentrant and interruptible and must have a
29 | * defined timeout mechanism.
30 | *
31 | * @author Marc-Olaf Jaschke
32 | *
33 | */
34 | public interface KeyLockManager {
35 |
36 | /**
37 | * Executes the given callback with protection against concurrent access for
38 | * the given key.
39 | *
40 | *
41 | * @param key
42 | * the key used to block concurrent access - must not be null
43 | * @param callback
44 | * the template to protect against concurrent access - must not
45 | * be null
46 | *
47 | * @throws KeyLockManagerInterruptedException
48 | * if the current thread becomes interrupted while waiting for a
49 | * lock
50 | * @throws KeyLockManagerTimeoutException
51 | * if the instance wide waiting time is exceeded, while waiting
52 | * for a lock
53 | */
54 | void executeLocked(Object key, LockCallback callback);
55 |
56 | /**
57 | * Executes the given callback with protection against concurrent access for
58 | * the given key and return the result of the computation done in the
59 | * callback
60 | *
61 | *
62 | * @param key
63 | * the key to block concurrent access - must not be null
64 | * @param callback
65 | * the template to protect against concurrent access - must not
66 | * be null
67 | *
68 | * @throws KeyLockManagerInterruptedException
69 | * if the current thread becomes interrupted while waiting for a
70 | * lock
71 | * @throws KeyLockManagerTimeoutException
72 | * if the instance wide waiting time is exceeded, while waiting
73 | * for lock
74 | *
75 | * @return result of the computation done in the callback
76 | */
77 | R executeLocked(Object key, ReturnValueLockCallback callback);
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/de/jkeylockmanager/manager/KeyLockManagers.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Marc-Olaf Jaschke
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 | * http://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 |
17 | package de.jkeylockmanager.manager;
18 |
19 | import de.jkeylockmanager.manager.implementation.lockstripe.StripedKeyLockManager;
20 |
21 | import java.util.concurrent.TimeUnit;
22 |
23 | /**
24 | *
25 | * This class contains factory methods to create new instances of {@link KeyLockManager}.
26 | *
27 | * @author Marc-Olaf Jaschke
28 | *
29 | */
30 | public final class KeyLockManagers {
31 |
32 | /**
33 | * Default lock wait time in seconds.
34 | */
35 | public static final int DEFAULT_LOCK_TIMEOUT = 1; // 1 h
36 |
37 |
38 | /**
39 | * Returns a new {@link KeyLockManager} with default settings. The best available multi purpose implementation is
40 | * used.
41 | *
42 | * @return the newly created lock
43 | */
44 | public static KeyLockManager newLock() {
45 | return new StripedKeyLockManager(DEFAULT_LOCK_TIMEOUT, TimeUnit.HOURS);
46 | }
47 |
48 | /**
49 | * Returns a new {@link KeyLockManager} with the given timeout settings. The best available multi purpose
50 | * implementation is used.
51 | *
52 | * @param lockTimeout
53 | * the time to wait for a lock before a Exception is thrown - must be greater than 0
54 | * @param lockTimeoutUnit
55 | * the unit for lockTimeout - must not be null
56 | *
57 | * @return the newly created lock
58 | */
59 | public static KeyLockManager newLock(final long lockTimeout, final TimeUnit lockTimeoutUnit) {
60 | return new StripedKeyLockManager(lockTimeout, lockTimeoutUnit);
61 | }
62 |
63 |
64 |
65 | /**
66 | * Prevent instantiation.
67 | */
68 | private KeyLockManagers() {
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/de/jkeylockmanager/manager/LockCallback.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Marc-Olaf Jaschke
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 | * http://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 |
17 | package de.jkeylockmanager.manager;
18 |
19 | /**
20 | * Implement this interface for callbacks without a return value, that should be
21 | * executed in a lock.
22 | *
23 | *
24 | * @author Marc-Olaf Jaschke
25 | *
26 | */
27 | public interface LockCallback {
28 |
29 | /**
30 | * This method is called inside the lock.
31 | *
32 | */
33 | void doInLock();
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/de/jkeylockmanager/manager/ReturnValueLockCallback.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Marc-Olaf Jaschke
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 | * http://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 |
17 | package de.jkeylockmanager.manager;
18 |
19 | /**
20 | * Implement this interface for callbacks with a return value, that should be
21 | * executed in a lock.
22 | *
23 | *
24 | * @author Marc-Olaf Jaschke
25 | *
26 | */
27 | public interface ReturnValueLockCallback {
28 |
29 | /**
30 | * This method is called inside the lock.
31 | *
32 | */
33 | R doInLock();
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/de/jkeylockmanager/manager/exception/KeyLockManagerException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Marc-Olaf Jaschke
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 | * http://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 |
17 | package de.jkeylockmanager.manager.exception;
18 |
19 | /**
20 | *
21 | * Superclass for all exceptions thrown in a key lock manager.
22 | *
23 | * @author Marc-Olaf Jaschke
24 | *
25 | */
26 | public abstract class KeyLockManagerException extends RuntimeException {
27 |
28 | private static final long serialVersionUID = -948800705345035397L;
29 |
30 | KeyLockManagerException(final String message) {
31 | super(message);
32 | }
33 |
34 | }
--------------------------------------------------------------------------------
/src/main/java/de/jkeylockmanager/manager/exception/KeyLockManagerInterruptedException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Marc-Olaf Jaschke
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 | * http://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 |
17 | package de.jkeylockmanager.manager.exception;
18 |
19 | /**
20 | * Exception to use, when a thread gets interrupted while waiting for a lock.
21 | *
22 | * @author Marc-Olaf Jaschke
23 | *
24 | */
25 | public class KeyLockManagerInterruptedException extends KeyLockManagerException {
26 |
27 | private static final long serialVersionUID = -2978888391122533260L;
28 |
29 | public KeyLockManagerInterruptedException() {
30 | super("interrupted while trying to acquire lock");
31 | }
32 | }
--------------------------------------------------------------------------------
/src/main/java/de/jkeylockmanager/manager/exception/KeyLockManagerTimeoutException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Marc-Olaf Jaschke
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 | * http://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 |
17 | package de.jkeylockmanager.manager.exception;
18 |
19 | import java.util.concurrent.TimeUnit;
20 |
21 | /**
22 | * Use this exception, if a thread has exceeded a timeout, while waiting for a
23 | * lock.
24 | *
25 | * @author Marc-Olaf Jaschke
26 | *
27 | */
28 | public class KeyLockManagerTimeoutException extends KeyLockManagerException {
29 |
30 | private static final long serialVersionUID = -9202899074196960232L;
31 |
32 | private final long timeout;
33 | private final TimeUnit timeUnit;
34 |
35 | public KeyLockManagerTimeoutException(final long timeout, final TimeUnit timeUnit) {
36 | super(String.format("timed out after %d [%s] while trying to acquire lock", timeout, timeUnit));
37 | this.timeout = timeout;
38 | this.timeUnit = timeUnit;
39 | }
40 |
41 | public long getTimeout() {
42 | return timeout;
43 | }
44 |
45 | public TimeUnit getTimeUnit() {
46 | return timeUnit;
47 | }
48 | }
--------------------------------------------------------------------------------
/src/main/java/de/jkeylockmanager/manager/implementation/lockstripe/CountingLock.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Marc-Olaf Jaschke
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 | * http://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 |
17 | package de.jkeylockmanager.manager.implementation.lockstripe;
18 |
19 | import java.util.concurrent.TimeUnit;
20 | import java.util.concurrent.locks.ReentrantLock;
21 |
22 | import de.jkeylockmanager.manager.exception.KeyLockManagerInterruptedException;
23 | import de.jkeylockmanager.manager.exception.KeyLockManagerTimeoutException;
24 |
25 | /**
26 | *
27 | * Special lock implementation for internal use in this package only.
28 | *
29 | * {@link CountingLock} adds a counter for counting its uses.
30 | *
31 | * The counting functionality is not thread safe and so it is essential to use
32 | * the following methods only in the scope of a shared lock:
33 | *
34 | * {@link #decrementUses()}, {@link #incrementUses()}, {@link #isUsed()}
35 | *
36 | *
37 | * @see ReentrantLock
38 | *
39 | * @author Marc-Olaf Jaschke
40 | *
41 | */
42 | final class CountingLock {
43 |
44 | private final ReentrantLock delegate = new ReentrantLock();
45 | private final long lockTimeout;
46 | private final TimeUnit lockTimeoutUnit;
47 | private long uses = 0;
48 |
49 | /**
50 | * Creates a new instance of {@link CountingLock} with a usage counter set
51 | * to zero.
52 | *
53 | * @param lockTimeout
54 | * - the time to wait for a lock before an Exception is thrown -
55 | * must be greater than 0
56 | * @param lockTimeoutUnit
57 | * - the unit for lockTimeout - must not be null
58 | */
59 | CountingLock(final long lockTimeout, final TimeUnit lockTimeoutUnit) {
60 | assert lockTimeout > 0 : "contract broken: lockTimeout > 0";
61 | assert lockTimeoutUnit != null : "contract broken: lockTimeoutUnit != null";
62 |
63 | this.lockTimeout = lockTimeout;
64 | this.lockTimeoutUnit = lockTimeoutUnit;
65 | }
66 |
67 | /**
68 | * Decrements the usage counter. See class commentary for thread safety!
69 | */
70 | void decrementUses() {
71 | uses--;
72 | }
73 |
74 | /**
75 | * Delegates to {@link ReentrantLock#getQueueLength()}
76 | */
77 | int getQueueLength() {
78 | return delegate.getQueueLength();
79 | }
80 |
81 | /**
82 | * Increments the usage counter. See class commentary for thread safety!
83 | */
84 | void incrementUses() {
85 | uses++;
86 | }
87 |
88 | /**
89 | * See class commentary for thread safety!
90 | *
91 | * @return true, if the usage counter is zero
92 | */
93 | boolean isUsed() {
94 | return uses != 0;
95 | }
96 |
97 | /**
98 | * Decorates {@link ReentrantLock#tryLock(long, TimeUnit)}.
99 | *
100 | * @throws KeyLockManagerInterruptedException
101 | * if the current thread becomes interrupted while waiting for
102 | * the lock
103 | * @throws KeyLockManagerTimeoutException
104 | * if the instance wide waiting time is exceeded
105 | */
106 | void tryLock() {
107 | try {
108 | if (!delegate.tryLock(lockTimeout, lockTimeoutUnit)) {
109 | throw new KeyLockManagerTimeoutException(lockTimeout, lockTimeoutUnit);
110 | }
111 | } catch (final InterruptedException e) {
112 | throw new KeyLockManagerInterruptedException();
113 | }
114 | }
115 |
116 | /**
117 | * Delegates to {@link java.util.concurrent.locks.ReentrantLock#unlock()}
118 | */
119 | void unlock() {
120 | delegate.unlock();
121 | }
122 |
123 | }
124 |
--------------------------------------------------------------------------------
/src/main/java/de/jkeylockmanager/manager/implementation/lockstripe/StripedKeyLockManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009 Marc-Olaf Jaschke
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 | * http://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 |
17 | package de.jkeylockmanager.manager.implementation.lockstripe;
18 |
19 | import de.jkeylockmanager.contract.Contract;
20 | import de.jkeylockmanager.manager.KeyLockManager;
21 | import de.jkeylockmanager.manager.LockCallback;
22 | import de.jkeylockmanager.manager.ReturnValueLockCallback;
23 |
24 | import java.util.concurrent.ConcurrentHashMap;
25 | import java.util.concurrent.TimeUnit;
26 |
27 | import static java.lang.Math.abs;
28 | import static java.util.Arrays.setAll;
29 |
30 | /**
31 | * Implementation of {@link KeyLockManager}.
32 | *
33 | * Maintenance operations are implemented using lock striping.
34 | *
35 | * All resources used by one key are freed immediately, if there is no longer a thread in the locked block for this key.
36 | *
37 | * @author Marc-Olaf Jaschke
38 | *
39 | */
40 | public final class StripedKeyLockManager implements KeyLockManager {
41 |
42 |
43 | /**
44 | * Default number of Stripes
45 | */
46 | private static final int DEFAULT_NUMBER_OF_STRIPES = 16;
47 |
48 |
49 | private final ConcurrentHashMap