|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.celeborn.client.util |
| 19 | + |
| 20 | +import java.util.concurrent.ConcurrentHashMap |
| 21 | + |
| 22 | +/** |
| 23 | + * This class is copied from Apache Spark. |
| 24 | + * A special locking mechanism to provide locking with a given key. By providing the same key |
| 25 | + * (identity is tested using the `equals` method), we ensure there is only one `func` running at |
| 26 | + * the same time. |
| 27 | + * |
| 28 | + * @tparam K the type of key to identify a lock. This type must implement `equals` and `hashCode` |
| 29 | + * correctly as it will be the key type of an internal Map. |
| 30 | + */ |
| 31 | +class KeyLock[K] { |
| 32 | + |
| 33 | + private val lockMap = new ConcurrentHashMap[K, AnyRef]() |
| 34 | + |
| 35 | + private def acquireLock(key: K): Unit = { |
| 36 | + while (true) { |
| 37 | + val lock = lockMap.putIfAbsent(key, new Object) |
| 38 | + if (lock == null) return |
| 39 | + lock.synchronized { |
| 40 | + while (lockMap.get(key) eq lock) { |
| 41 | + lock.wait() |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private def releaseLock(key: K): Unit = { |
| 48 | + val lock = lockMap.remove(key) |
| 49 | + lock.synchronized { |
| 50 | + lock.notifyAll() |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Run `func` under a lock identified by the given key. Multiple calls with the same key |
| 56 | + * (identity is tested using the `equals` method) will be locked properly to ensure there is only |
| 57 | + * one `func` running at the same time. |
| 58 | + */ |
| 59 | + def withLock[T](key: K)(func: => T): T = { |
| 60 | + if (key == null) { |
| 61 | + throw new NullPointerException("key must not be null") |
| 62 | + } |
| 63 | + acquireLock(key) |
| 64 | + try { |
| 65 | + func |
| 66 | + } finally { |
| 67 | + releaseLock(key) |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments