1 package org.eclipse.aether.named; 2 3 /* 4 * Licensed to the Apache Software Foundation (ASF) under one 5 * or more contributor license agreements. See the NOTICE file 6 * distributed with this work for additional information 7 * regarding copyright ownership. The ASF licenses this file 8 * to you under the Apache License, Version 2.0 (the 9 * "License"); you may not use this file except in compliance 10 * with the License. You may obtain a copy of the License at 11 * 12 * http://www.apache.org/licenses/LICENSE-2.0 13 * 14 * Unless required by applicable law or agreed to in writing, 15 * software distributed under the License is distributed on an 16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 * KIND, either express or implied. See the License for the 18 * specific language governing permissions and limitations 19 * under the License. 20 */ 21 22 import java.util.concurrent.TimeUnit; 23 24 /** 25 * A named lock, functionally similar to existing JVM and other implementations. Must support boxing (reentrancy), but 26 * no lock upgrade is supported. The lock instance obtained from lock factory must be treated as a resource, best in 27 * try-with-resource block. Usual pattern to use this lock: 28 * <pre> 29 * try (NamedLock lock = factory.getLock("resourceName")) { 30 * if (lock.lockExclusively(10L, Timeunit.SECONDS)) { 31 * try { 32 * ... exclusive access to "resourceName" resource gained here 33 * } 34 * finally { 35 * lock.unlock(); 36 * } 37 * } 38 * else { 39 * ... failed to gain access within specified time, handle it 40 * } 41 * } 42 * </pre> 43 */ 44 public interface NamedLock extends AutoCloseable 45 { 46 /** 47 * Returns this instance name, never null 48 */ 49 String name(); 50 51 /** 52 * Tries to lock shared, may block for given time. If successful, returns {@code true}. 53 */ 54 boolean lockShared( long time, TimeUnit unit ) throws InterruptedException; 55 56 /** 57 * Tries to lock exclusively, may block for given time. If successful, returns {@code true}. 58 */ 59 boolean lockExclusively( long time, TimeUnit unit ) throws InterruptedException; 60 61 /** 62 * Unlocks the lock, must be invoked by caller after one of the {@link #lockShared(long, TimeUnit)} or {@link 63 * #lockExclusively(long, TimeUnit)}. 64 */ 65 void unlock(); 66 67 /** 68 * Closes the lock resource. Lock MUST be unlocked using {@link #unlock()} in case any locking happened on it. After 69 * invoking this method, the lock instance MUST NOT be used anymore. If lock for same name needed, a new instance 70 * should be obtained from factory using {@link NamedLockFactory#getLock(String)}. Ideally, instances are to be used 71 * within try-with-resource blocks, so calling this method directly is not really needed, nor advised. 72 */ 73 @Override 74 void close(); 75 }