001/* 002 * PlotSquared, a land and world management plugin for Minecraft. 003 * Copyright (C) IntellectualSites <https://intellectualsites.com> 004 * Copyright (C) IntellectualSites team and contributors 005 * 006 * This program is free software: you can redistribute it and/or modify 007 * it under the terms of the GNU General Public License as published by 008 * the Free Software Foundation, either version 3 of the License, or 009 * (at your option) any later version. 010 * 011 * This program is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 014 * GNU General Public License for more details. 015 * 016 * You should have received a copy of the GNU General Public License 017 * along with this program. If not, see <https://www.gnu.org/licenses/>. 018 */ 019package com.plotsquared.core.synchronization; 020 021import com.google.common.base.Objects; 022import com.google.common.base.Preconditions; 023import org.checkerframework.checker.nullness.qual.NonNull; 024 025import java.util.Collection; 026import java.util.Collections; 027import java.util.HashMap; 028import java.util.Map; 029 030/** 031 * Key used to access {@link java.util.concurrent.locks.Lock locks} 032 * from a {@link LockRepository} 033 */ 034public final class LockKey { 035 036 private static final Map<String, LockKey> keyMap = new HashMap<>(); 037 private static final Object keyLock = new Object(); 038 039 private final String key; 040 041 private LockKey(final @NonNull String key) { 042 this.key = Preconditions.checkNotNull(key, "Key may not be null"); 043 } 044 045 /** 046 * Get a new named lock key 047 * 048 * @param key Key name 049 * @return Lock key instance 050 */ 051 public static @NonNull LockKey of(final @NonNull String key) { 052 synchronized (keyLock) { 053 return keyMap.computeIfAbsent(key, LockKey::new); 054 } 055 } 056 057 /** 058 * Get all currently recognized lock keys 059 * 060 * @return Currently recognized lock keys 061 */ 062 @NonNull 063 static Collection<LockKey> recognizedKeys() { 064 return Collections.unmodifiableCollection(keyMap.values()); 065 } 066 067 @Override 068 public String toString() { 069 return "LockKey{" + "key='" + key + '\'' + '}'; 070 } 071 072 @Override 073 public boolean equals(final Object o) { 074 if (this == o) { 075 return true; 076 } 077 if (o == null || getClass() != o.getClass()) { 078 return false; 079 } 080 final LockKey lockKey = (LockKey) o; 081 return Objects.equal(this.key, lockKey.key); 082 } 083 084 @Override 085 public int hashCode() { 086 return Objects.hashCode(this.key); 087 } 088 089}