├── .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 | [![Build Status](https://travis-ci.org/mojgh/JKeyLockManager.svg?branch=master)](https://travis-ci.org/mojgh/JKeyLockManager) 120 | 121 | #### version-1 122 | [![Build Status](https://travis-ci.org/mojgh/JKeyLockManager.svg?branch=version-1)](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 | lock-chart -------------------------------------------------------------------------------- /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 key2lock = new ConcurrentHashMap<>(); 50 | private final CountingLock[] stripes; 51 | private final long lockTimeout; 52 | private final TimeUnit lockTimeoutUnit; 53 | 54 | 55 | /** 56 | * Creates a new instance of {@link StripedKeyLockManager} with the a default number of stripes 57 | * 58 | * see #StripedKeyLockManager(long, java.util.concurrent.TimeUnit, int) 59 | * 60 | */ 61 | public StripedKeyLockManager(final long lockTimeout, final TimeUnit lockTimeoutUnit) { 62 | this(lockTimeout, lockTimeoutUnit, DEFAULT_NUMBER_OF_STRIPES); 63 | } 64 | 65 | /** 66 | * Creates a new instance of {@link StripedKeyLockManager} with the given settings. 67 | * 68 | * @param lockTimeout 69 | * the time to wait for a lock before a Exception is thrown - must be greater than 0 70 | * @param lockTimeoutUnit 71 | * the unit for lockTimeout - must not be null 72 | * @param numberOfStripes 73 | * the number of stripes used for locking 74 | */ 75 | public StripedKeyLockManager(final long lockTimeout, final TimeUnit lockTimeoutUnit, final int numberOfStripes) { 76 | Contract.isNotNull(lockTimeoutUnit, "lockTimeoutUnit != null"); 77 | Contract.isTrue(lockTimeout > 0, "lockTimeout > 0"); 78 | Contract.isTrue(numberOfStripes > 0, "numberOfStripes > 0"); 79 | 80 | this.lockTimeout = lockTimeout; 81 | this.lockTimeoutUnit = lockTimeoutUnit; 82 | this.stripes = new CountingLock[numberOfStripes]; 83 | 84 | setAll(stripes, i -> new CountingLock(lockTimeout, lockTimeoutUnit)); 85 | } 86 | 87 | 88 | @Override 89 | public final void executeLocked(final Object key, final LockCallback callback) { 90 | Contract.isNotNull(key, "key != null"); 91 | Contract.isNotNull(callback, "callback != null"); 92 | 93 | executeLockedInternal(key, () -> { 94 | callback.doInLock(); 95 | return null; 96 | }); 97 | 98 | } 99 | 100 | @Override 101 | public final R executeLocked(final Object key, final ReturnValueLockCallback callback) { 102 | Contract.isNotNull(key, "key != null"); 103 | Contract.isNotNull(callback, "callback != null"); 104 | 105 | return executeLockedInternal(key, callback); 106 | } 107 | 108 | 109 | private R executeLockedInternal(final Object key, final ReturnValueLockCallback callback) { 110 | assert key != null : "contract broken: key != null"; 111 | assert callback != null : "contract broken: callback != null"; 112 | 113 | final CountingLock lock = getKeyLock(key); 114 | try { 115 | lock.tryLock(); 116 | try { 117 | return callback.doInLock(); 118 | } finally { 119 | lock.unlock(); 120 | } 121 | } finally { 122 | freeKeyLock(key, lock); 123 | } 124 | } 125 | 126 | private void freeKeyLock(final Object key, final CountingLock lock) { 127 | assert key != null : "contract broken: key != null"; 128 | assert lock != null : "contract broken: lock != null"; 129 | getStripedLock(key).tryLock(); 130 | try { 131 | lock.decrementUses(); 132 | if (!lock.isUsed()) { 133 | key2lock.remove(key); 134 | } 135 | } finally { 136 | getStripedLock(key).unlock(); 137 | } 138 | } 139 | 140 | private CountingLock getKeyLock(final Object key) { 141 | assert key != null : "contract broken: key != null"; 142 | getStripedLock(key).tryLock(); 143 | try { 144 | final CountingLock result; 145 | final CountingLock previousLock = key2lock.get(key); 146 | if (previousLock == null) { 147 | result = new CountingLock(lockTimeout, lockTimeoutUnit); 148 | key2lock.put(key, result); 149 | } else { 150 | result = previousLock; 151 | } 152 | result.incrementUses(); 153 | return result; 154 | } finally { 155 | getStripedLock(key).unlock(); 156 | } 157 | } 158 | 159 | private CountingLock getStripedLock(final Object key) { 160 | assert key != null : "contract broken: key != null"; 161 | return stripes[abs(key.hashCode() % stripes.length)]; 162 | } 163 | 164 | /** 165 | * for testing only 166 | * 167 | * @return the number of currently active key locks 168 | * 169 | */ 170 | int activeKeyLocksCount() { 171 | return key2lock.size(); 172 | } 173 | 174 | /** 175 | * for testing only 176 | * 177 | * @return the number of threads currently waiting in the queues of the key locks 178 | */ 179 | int waitingThreadsCount() { 180 | int result = 0; 181 | for (final CountingLock lock : key2lock.values()) { 182 | result += lock.getQueueLength(); 183 | } 184 | return result; 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /src/test/java/de/jkeylockmanager/contract/ContractTest.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 | import org.junit.Assert; 20 | import org.junit.Test; 21 | 22 | import static org.junit.Assert.assertEquals; 23 | import static org.junit.Assert.fail; 24 | 25 | /** 26 | * 27 | * @author Marc-Olaf Jaschke 28 | * 29 | */ 30 | public class ContractTest { 31 | 32 | private static final String MESSAGE = "message"; 33 | 34 | @Test 35 | public void testAssertIsTrue() throws Exception { 36 | 37 | Contract.isTrue(true, MESSAGE); 38 | 39 | try { 40 | Contract.isTrue(false, MESSAGE); 41 | fail(); 42 | } catch (final ContractBrokenError e) { 43 | assertEquals(String.format("contract broken: %s", MESSAGE), e.getMessage()); 44 | } 45 | 46 | } 47 | 48 | @Test 49 | public void testAssertNotNull() throws Exception { 50 | 51 | Contract.isNotNull("", MESSAGE); 52 | 53 | try { 54 | Contract.isNotNull(null, MESSAGE); 55 | fail(); 56 | } catch (final ContractBrokenError e) { 57 | assertEquals(String.format("contract broken: %s", MESSAGE), e.getMessage()); 58 | } 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/de/jkeylockmanager/manager/implementation/lockstripe/StripedKeyLockManagerTest.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.manager.exception.KeyLockManagerException; 20 | import de.jkeylockmanager.manager.exception.KeyLockManagerInterruptedException; 21 | import de.jkeylockmanager.manager.exception.KeyLockManagerTimeoutException; 22 | import org.junit.Test; 23 | 24 | import java.util.concurrent.CountDownLatch; 25 | import java.util.concurrent.Exchanger; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import static java.lang.Thread.sleep; 29 | import static org.hamcrest.Matchers.instanceOf; 30 | import static org.junit.Assert.*; 31 | 32 | /** 33 | * 34 | * @author Marc-Olaf Jaschke 35 | * 36 | */ 37 | public class StripedKeyLockManagerTest { 38 | 39 | private static class TestException extends RuntimeException { 40 | private static final long serialVersionUID = -7939021299106344924L; 41 | } 42 | 43 | private void assertCleanup(final StripedKeyLockManager lock) { 44 | assertEquals("not all locks were released", 0, lock.activeKeyLocksCount()); 45 | } 46 | 47 | /** 48 | * one thread holds a lock on one key - a second thread waits to acquire the 49 | * lock on the same key - the first thread throws an exception - the second 50 | * thread acquires the lock 51 | */ 52 | @Test 53 | public void testExceptionInWorkUnit() throws Exception { 54 | 55 | final StripedKeyLockManager manager = new StripedKeyLockManager(Long.MAX_VALUE, TimeUnit.SECONDS); 56 | 57 | final CountDownLatch t1WorkUnitEntry = new CountDownLatch(1); 58 | final CountDownLatch t1ThrowException = new CountDownLatch(1); 59 | 60 | final Thread t1 = new Thread(() -> { 61 | try { 62 | manager.executeLocked("test1", () -> { 63 | try { 64 | t1WorkUnitEntry.countDown(); 65 | t1ThrowException.await(); 66 | throw new TestException(); 67 | } catch (final InterruptedException ignored) { 68 | } 69 | }); 70 | fail(); 71 | } catch (TestException ignored) { 72 | } 73 | }); 74 | 75 | t1.start(); 76 | 77 | t1WorkUnitEntry.await(); 78 | 79 | // t2 should enter the work unit after t1 throws the exception 80 | 81 | final Thread t2 = new Thread(() -> manager.executeLocked("test1", () -> {})); 82 | 83 | t2.start(); 84 | 85 | while (manager.waitingThreadsCount() < 1) { 86 | sleep(10); 87 | } 88 | 89 | t1ThrowException.countDown(); 90 | 91 | t2.join(); 92 | 93 | t1.interrupt(); 94 | t1.join(); 95 | 96 | assertCleanup(manager); 97 | } 98 | 99 | /** 100 | * one thread holds a lock on one key -> a second thread waits on the same 101 | * key and becomes interrupted while waiting -> t2 must throw a special 102 | * exception 103 | */ 104 | @Test 105 | public void testInterruptReaction() throws Exception { 106 | 107 | final StripedKeyLockManager manager = new StripedKeyLockManager(Long.MAX_VALUE, TimeUnit.SECONDS); 108 | 109 | final CountDownLatch t1WorkUnitEntry = new CountDownLatch(1); 110 | 111 | final Thread t1 = new Thread(() -> 112 | manager.executeLocked("test", () -> { 113 | try { 114 | t1WorkUnitEntry.countDown(); 115 | sleep(Long.MAX_VALUE); 116 | } catch (final InterruptedException ignored) { 117 | } 118 | })); 119 | 120 | t1.start(); 121 | 122 | t1WorkUnitEntry.await(); 123 | 124 | // t2 waits for t1 before entering the work unit and gets interrupted 125 | // while waiting 126 | 127 | final Exchanger exchanger = new Exchanger<>(); 128 | final Thread t2 = new Thread(() -> { 129 | try { 130 | manager.executeLocked("test", () -> {}); 131 | } catch (final KeyLockManagerException e) { 132 | try { 133 | exchanger.exchange(e); 134 | } catch (final InterruptedException ignored) { 135 | } 136 | } 137 | }); 138 | 139 | t2.start(); 140 | 141 | while (manager.waitingThreadsCount() < 1) { 142 | sleep(10); 143 | } 144 | 145 | t2.interrupt(); 146 | 147 | assertThat(exchanger.exchange(null), instanceOf(KeyLockManagerInterruptedException.class)); 148 | 149 | t1.interrupt(); 150 | t1.join(); 151 | t2.join(); 152 | 153 | assertCleanup(manager); 154 | } 155 | 156 | /** 157 | * one thread holds a lock on one key, a second thread on an other key must 158 | * not block 159 | */ 160 | @Test 161 | public void testLockWithDifferentKeys() throws Exception { 162 | 163 | final StripedKeyLockManager manager = new StripedKeyLockManager(Long.MAX_VALUE, TimeUnit.SECONDS); 164 | 165 | final CountDownLatch t1WorkUnitEntry = new CountDownLatch(1); 166 | final CountDownLatch t2WorkUnitEntry = new CountDownLatch(1); 167 | 168 | final Thread t1 = new Thread(() -> 169 | manager.executeLocked("test1", () -> { 170 | try { 171 | t1WorkUnitEntry.countDown(); 172 | sleep(Long.MAX_VALUE); 173 | } catch (final InterruptedException ignored) { 174 | } 175 | })); 176 | 177 | t1.start(); 178 | 179 | t1WorkUnitEntry.await(); 180 | 181 | assertEquals(0, manager.waitingThreadsCount()); 182 | 183 | // t2 should not wait for t1 to enter the work unit 184 | 185 | final Thread t2 = new Thread(() -> 186 | manager.executeLocked("test2", () -> { 187 | try { 188 | t2WorkUnitEntry.countDown(); 189 | Thread.sleep(Long.MAX_VALUE); 190 | } catch (final InterruptedException ignored) { 191 | } 192 | })); 193 | 194 | t2.start(); 195 | 196 | // blocks for many days, if 'test2' is blocked by 'test1' 197 | t2WorkUnitEntry.await(); 198 | 199 | t1.interrupt(); 200 | t2.interrupt(); 201 | t1.join(); 202 | t2.join(); 203 | 204 | assertCleanup(manager); 205 | } 206 | 207 | /** 208 | * one thread holds a lock on one key and a other thread is waiting to 209 | * acquire the lock in the same key - the first thread gets interrupted and 210 | * the second can acquire the lock 211 | */ 212 | @Test 213 | public void testLockWithOneKey() throws Exception { 214 | 215 | final StripedKeyLockManager manager = new StripedKeyLockManager(Long.MAX_VALUE, TimeUnit.SECONDS); 216 | 217 | final CountDownLatch t1WorkUnitEntry = new CountDownLatch(1); 218 | 219 | final Thread t1 = new Thread(() -> 220 | manager.executeLocked("test", () -> { 221 | try { 222 | t1WorkUnitEntry.countDown(); 223 | sleep(Long.MAX_VALUE); 224 | } catch (final InterruptedException ignored) { 225 | } 226 | })); 227 | 228 | t1.start(); 229 | 230 | t1WorkUnitEntry.await(); 231 | 232 | assertEquals(0, manager.waitingThreadsCount()); 233 | 234 | // t2 waits for t1 to become interrupted to enter the work unit 235 | 236 | final Thread t2 = new Thread(() -> { 237 | try { 238 | manager.executeLocked("test", () -> {}); 239 | } catch (final KeyLockManagerInterruptedException ignored) { 240 | } 241 | }); 242 | t2.start(); 243 | 244 | while (manager.waitingThreadsCount() < 1) { 245 | sleep(10); 246 | } 247 | 248 | assertEquals(1, manager.waitingThreadsCount()); 249 | 250 | t1.interrupt(); 251 | t1.join(); 252 | 253 | // wait many days if the lock is not freed after interruption of t1 254 | t2.join(); 255 | 256 | assertCleanup(manager); 257 | } 258 | 259 | /** 260 | * one thread holds a lock for one key while holding a lock on an other key 261 | */ 262 | @Test 263 | public void testNestedUse() throws Exception { 264 | 265 | final StripedKeyLockManager manager = new StripedKeyLockManager(500, TimeUnit.MILLISECONDS); 266 | 267 | final CountDownLatch workUnitEntry = new CountDownLatch(1); 268 | final CountDownLatch workUnitExit = new CountDownLatch(1); 269 | 270 | final Thread t1 = new Thread(() -> 271 | manager.executeLocked("test", () -> 272 | manager.executeLocked("test2", () -> { 273 | try { 274 | workUnitEntry.countDown(); 275 | workUnitExit.await(); 276 | } catch (final InterruptedException e) { 277 | e.printStackTrace(); 278 | } 279 | }))); 280 | 281 | t1.start(); 282 | 283 | workUnitEntry.await(); // waits many days if lock is not released 284 | 285 | assertEquals(2, manager.activeKeyLocksCount()); 286 | assertEquals(0, manager.waitingThreadsCount()); 287 | 288 | workUnitExit.countDown(); 289 | 290 | t1.join(); 291 | 292 | assertCleanup(manager); 293 | } 294 | 295 | /** 296 | * one thread enters a locked block for one key while holding a lock block 297 | * on the same key 298 | */ 299 | @Test 300 | public void testReentrantBehavior() throws Exception { 301 | 302 | final StripedKeyLockManager manager = new StripedKeyLockManager(10, TimeUnit.SECONDS); 303 | 304 | final CountDownLatch workUnitEntry = new CountDownLatch(1); 305 | final CountDownLatch workUnitExit = new CountDownLatch(1); 306 | 307 | final Thread t1 = new Thread(() -> 308 | manager.executeLocked("test", () -> 309 | manager.executeLocked("test", () -> 310 | { 311 | try { 312 | workUnitEntry.countDown(); 313 | workUnitExit.await(); 314 | } catch (final InterruptedException e) { 315 | e.printStackTrace(); 316 | } 317 | }))); 318 | 319 | t1.start(); 320 | 321 | workUnitEntry.await(); // waits 10s, if lock is not released 322 | 323 | assertEquals(1, manager.activeKeyLocksCount()); 324 | assertEquals(0, manager.waitingThreadsCount()); 325 | 326 | workUnitExit.countDown(); 327 | 328 | t1.join(); 329 | 330 | assertCleanup(manager); 331 | } 332 | 333 | /** 334 | * one thread holds a lock on a key - a second thread waits to acquire the 335 | * lock on the same key - the seconds thread stops waiting after a timeout 336 | */ 337 | @Test 338 | public void testTimeoutReaction() throws Exception { 339 | 340 | final StripedKeyLockManager manager = new StripedKeyLockManager(500, TimeUnit.MILLISECONDS); 341 | 342 | final CountDownLatch t1WorkUnitEntry = new CountDownLatch(1); 343 | 344 | final Thread t1 = new Thread(() -> 345 | manager.executeLocked("test", () -> { 346 | try { 347 | t1WorkUnitEntry.countDown(); 348 | sleep(Long.MAX_VALUE); 349 | } catch (final InterruptedException ignored) { 350 | } 351 | })); 352 | t1.start(); 353 | 354 | t1WorkUnitEntry.await(); 355 | 356 | // t2 waits for t1 to enter the work unit and should timeout 357 | 358 | final Exchanger exchanger = new Exchanger<>(); 359 | 360 | final Thread t2 = new Thread(() -> { 361 | try { 362 | manager.executeLocked("test", () -> { }); 363 | } catch (final KeyLockManagerException e) { 364 | try { 365 | exchanger.exchange(e); 366 | } catch (final InterruptedException ignored) { 367 | } 368 | } 369 | }); 370 | t2.start(); 371 | 372 | assertThat(exchanger.exchange(null), instanceOf(KeyLockManagerTimeoutException.class)); 373 | 374 | assertEquals("lock was disposed to early", 1, manager.activeKeyLocksCount()); 375 | 376 | t1.interrupt(); 377 | t1.join(); 378 | 379 | assertCleanup(manager); 380 | } 381 | 382 | /** 383 | * one thread holds a lock on one key - a second thread waits to acquire the 384 | * lock on the same key - the first thread releases the lock - the second 385 | * thread enters the lock 386 | */ 387 | @Test 388 | public void testUnlockAfterNormalWorkUnitExit() throws Exception { 389 | 390 | final StripedKeyLockManager manager = new StripedKeyLockManager(500, TimeUnit.MILLISECONDS); 391 | 392 | final CountDownLatch t1WorkUnitEntry = new CountDownLatch(1); 393 | final CountDownLatch t1SignalToExit = new CountDownLatch(1); 394 | 395 | final Thread t1 = new Thread(() -> 396 | manager.executeLocked("test", () -> { 397 | try { 398 | t1WorkUnitEntry.countDown(); 399 | t1SignalToExit.await(); 400 | } catch (final InterruptedException ignored) { 401 | } 402 | })); 403 | t1.start(); 404 | 405 | t1WorkUnitEntry.await(); 406 | 407 | final Thread t2 = new Thread(() -> manager.executeLocked("test", () -> { })); 408 | t2.start(); 409 | 410 | while (manager.waitingThreadsCount() < 1) { 411 | sleep(10); 412 | } 413 | 414 | t1SignalToExit.countDown(); 415 | 416 | t1.join(); 417 | t2.join(); // t2 waits many days if lock is not released 418 | 419 | assertCleanup(manager); 420 | } 421 | 422 | @Test 423 | public void testWithReturnValueCallback() { 424 | final StripedKeyLockManager manager = new StripedKeyLockManager(10, TimeUnit.SECONDS); 425 | 426 | assertEquals(Integer.valueOf(20), manager.executeLocked("test", () -> 20)); 427 | 428 | assertCleanup(manager); 429 | } 430 | } 431 | -------------------------------------------------------------------------------- /src/testslow/java/de/jkeylockmanager/manager/implementation/lockstripe/StripedKeyLockManagerStressTest.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.manager.KeyLockManager; 20 | import org.junit.Test; 21 | 22 | import java.util.*; 23 | import java.util.Map.Entry; 24 | import java.util.concurrent.*; 25 | 26 | import static java.lang.Thread.sleep; 27 | import static org.junit.Assert.*; 28 | 29 | /** 30 | * Stress test for {@link StripedKeyLockManager}. 31 | * 32 | * @author Marc-Olaf Jaschke 33 | * 34 | */ 35 | public class StripedKeyLockManagerStressTest { 36 | 37 | private static final int LOCK_TIMEOUT = 1; 38 | private static final int DIFFERENT_KEYS = 5; 39 | private static final int THREAD_COUNT = 200; 40 | private static final int INVOCATIONS_PER_THREAD = 1000; 41 | 42 | 43 | @Test 44 | public void testDoLocked() throws InterruptedException { 45 | 46 | final StripedKeyLockManager manager = new StripedKeyLockManager(LOCK_TIMEOUT, TimeUnit.HOURS); 47 | final WeatherService service = new WeatherService(); 48 | final WeatherServiceProxy serviceProxy = new WeatherServiceProxy(service, manager); 49 | 50 | final List keys = new ArrayList<>(); 51 | for (int i = 0; i < DIFFERENT_KEYS; i++) { 52 | keys.add(Integer.toString(i)); 53 | } 54 | 55 | final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); 56 | 57 | final CyclicBarrier waitForOtherThreads = new CyclicBarrier(THREAD_COUNT); 58 | 59 | for (int i = 0; i < THREAD_COUNT; i++) { 60 | executorService.execute(new TestThread(serviceProxy, keys, waitForOtherThreads)); 61 | } 62 | 63 | executorService.shutdown(); 64 | if (!executorService.awaitTermination(10, TimeUnit.MINUTES)) { 65 | fail("executor service failed to shutdown"); 66 | } 67 | 68 | assertFalse(service.concurrentUpdatesPerKey()); 69 | 70 | assertEquals("all locks must me disposed", 0, manager.activeKeyLocksCount()); 71 | 72 | } 73 | 74 | 75 | private interface IWeatherService { 76 | void updateWeatherData(String cityName); 77 | } 78 | 79 | private static class TestThread implements Runnable { 80 | 81 | private final IWeatherService service; 82 | private final List keys; 83 | private final Random random = new Random(); 84 | private final CyclicBarrier waitForOtherThreads; 85 | 86 | public TestThread(final IWeatherService service, final List keys, final CyclicBarrier waitForOtherThreads) { 87 | this.service = service; 88 | this.keys = new ArrayList<>(keys); 89 | this.waitForOtherThreads = waitForOtherThreads; 90 | } 91 | 92 | @Override 93 | public void run() { 94 | try { 95 | waitForOtherThreads.await(); 96 | for (int i = 0; i < INVOCATIONS_PER_THREAD; i++) { 97 | final String key = keys.get(random.nextInt(keys.size())); 98 | service.updateWeatherData(key); 99 | } 100 | } catch (final InterruptedException | BrokenBarrierException e) { 101 | e.printStackTrace(); 102 | } 103 | } 104 | } 105 | 106 | private static class WeatherService implements IWeatherService { 107 | 108 | private final Map invocationsSafe = new HashMap<>(); 109 | private final Map invocationsUnsafe = new ConcurrentHashMap<>(); 110 | 111 | public boolean concurrentUpdatesPerKey() { 112 | boolean result = false; 113 | for (final Entry entry : invocationsSafe.entrySet()) { 114 | if (!entry.getValue().equals(invocationsUnsafe.get(entry.getKey()))) { 115 | result = true; 116 | break; 117 | } 118 | } 119 | return result; 120 | } 121 | 122 | @Override 123 | public void updateWeatherData(final String cityName) { 124 | synchronized (this) { 125 | incCounter(cityName, invocationsSafe, false); 126 | } 127 | incCounter(cityName, invocationsUnsafe, true); 128 | } 129 | 130 | private void incCounter(final String cityName, final Map invocations, final boolean wait) { 131 | final Integer count = invocations.get(cityName); 132 | if (wait) { 133 | try { 134 | sleep(0, 10); 135 | } catch (final InterruptedException e) { 136 | throw new RuntimeException(e); 137 | } 138 | } 139 | invocations.put(cityName, count == null ? 1 : count + 1); 140 | } 141 | } 142 | 143 | private static class WeatherServiceProxy implements IWeatherService { 144 | 145 | private final IWeatherService delegate; 146 | private final KeyLockManager lock; 147 | 148 | public WeatherServiceProxy(final IWeatherService delegate, final KeyLockManager lock) { 149 | this.delegate = delegate; 150 | this.lock = lock; 151 | } 152 | 153 | @Override 154 | public void updateWeatherData(final String cityName) { 155 | lock.executeLocked(cityName, () -> delegate.updateWeatherData(cityName)); 156 | } 157 | 158 | } 159 | } 160 | --------------------------------------------------------------------------------