|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +package org.commonwl.view.git; |
| 21 | + |
| 22 | +import org.springframework.stereotype.Component; |
| 23 | + |
| 24 | +import java.util.HashMap; |
| 25 | +import java.util.Map; |
| 26 | + |
| 27 | +/** |
| 28 | + * Object to manage concurrent access to Git repositories |
| 29 | + */ |
| 30 | +@Component |
| 31 | +public class GitSemaphore { |
| 32 | + |
| 33 | + private static Map<String, Integer> currentRepos = new HashMap<>(); |
| 34 | + |
| 35 | + /** |
| 36 | + * Note that a thread will be accessing the repository |
| 37 | + * @param repoUrl The url of the repository |
| 38 | + * @return Whether the resource can be accessed safely |
| 39 | + * (no other threads are using it) |
| 40 | + */ |
| 41 | + synchronized boolean acquire(String repoUrl) { |
| 42 | + if (currentRepos.containsKey(repoUrl)) { |
| 43 | + currentRepos.put(repoUrl, currentRepos.get(repoUrl) + 1); |
| 44 | + return false; |
| 45 | + } else { |
| 46 | + currentRepos.put(repoUrl, 1); |
| 47 | + return true; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Release use of the shared resource |
| 53 | + * @param repoUrl The url of the repository |
| 54 | + */ |
| 55 | + synchronized void release(String repoUrl) { |
| 56 | + if (currentRepos.containsKey(repoUrl)) { |
| 57 | + int threadCountUsing = currentRepos.get(repoUrl); |
| 58 | + if (threadCountUsing > 1) { |
| 59 | + currentRepos.put(repoUrl, threadCountUsing - 1); |
| 60 | + } else { |
| 61 | + currentRepos.remove(repoUrl); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments