
com.hazelcast.util.ContextMutexFactory Maven / Gradle / Ivy
/*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.util;
import java.io.Closeable;
import java.util.HashMap;
import java.util.Map;
/**
* Utility class that provides reference-counted mutexes suitable for synchronization in the context of a supplied object.
* Context objects and their associated mutexes are stored in a {@code Map}. Client code is responsible to invoke
* {@link Mutex#close()} on the obtained {@code Mutex} after having synchronized on the mutex; failure to do so, will leave an
* entry residing in the internal {@code Map} which may have adverse effects on the ability to garbage collect the context object
* and the mutex. The returned {@link Mutex}es implement Closeable, so can be conveniently used in a try-with-resources statement.
* Typical usage would allow, for example, synchronizing access to a non-thread-safe {@code Map} on a per-key basis,
* to avoid blocking other threads who would perform updates on other entries of the {@code Map}.
*
* class Test {
*
* private static final ContextMutexFactory mutexFactory = new ContextMutexFactory();
* private Map<String, String> mapToSync = new HashMap<String, String>();
*
* public void test(String key, String value) {
* // critical section
* ContextMutexFactory.Mutex mutex = mutexFactory.mutexFor(key);
* try {
* synchronized (mutex) {
* if (mapToSync.get(key) == null) {
* mapToSync.put(key, value);
* }
* }
* }
* finally {
* mutex.close();
* }
* }
* }
*
*
*/
public final class ContextMutexFactory {
Map
© 2015 - 2025 Weber Informatics LLC | Privacy Policy