001/*
002 * (C) Copyright 2017 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Funsho David
018 *
019 */
020
021package org.nuxeo.ecm.core.api;
022
023import org.nuxeo.runtime.api.Framework;
024import org.nuxeo.runtime.kv.KeyValueService;
025import org.nuxeo.runtime.kv.KeyValueStore;
026import org.nuxeo.runtime.transaction.TransactionHelper;
027
028import java.util.function.Supplier;
029
030/**
031 * Utilities to work with locks
032 *
033 * @since 9.3
034 */
035public class LockHelper {
036
037    public static final String DOCUMENT_LOCK = "document-lock";
038
039    public static final String LOCK = "lock";
040
041    public static final int NB_TRY = 3;
042
043    public static final int SLEEP_DURATION = 1000;
044
045    private LockHelper() {
046    }
047
048    /**
049     * Runs a {@link Runnable} atomically, in a cluster-wide critical section.
050     *
051     * @param key the key used to determine atomicity
052     * @param runnable the runnable
053     */
054    public static void doAtomically(String key, Runnable runnable) throws ConcurrentUpdateException {
055        doAtomically(key, () -> {
056            runnable.run();
057            return null;
058        });
059    }
060
061    /**
062     * Runs a {@link Supplier} atomically, in a cluster-wide critical section.
063     *
064     * @param key the key used to determine atomicity
065     * @param supplier the supplier
066     * @return the result of the function
067     */
068    public static <R> R doAtomically(String key, Supplier<R> supplier) throws ConcurrentUpdateException {
069
070        KeyValueStore kvStore = Framework.getService(KeyValueService.class).getKeyValueStore(DOCUMENT_LOCK);
071
072        try {
073            if (tryLock(key, kvStore)) {
074                try {
075                    TransactionHelper.commitOrRollbackTransaction();
076                    TransactionHelper.startTransaction();
077
078                    return supplier.get();
079                } finally {
080                    try {
081                        TransactionHelper.commitOrRollbackTransaction();
082                        TransactionHelper.startTransaction();
083                    } finally {
084                        unlock(key, kvStore);
085                    }
086                }
087            } else {
088                throw new ConcurrentUpdateException("Failed to acquire the lock on key " + key);
089            }
090        } catch (InterruptedException e) {
091            Thread.currentThread().interrupt();
092            throw new NuxeoException(e);
093        }
094    }
095
096    protected static boolean tryLock(String key, KeyValueStore kvStore) throws InterruptedException {
097        // Try to acquire the lock and fail if it takes too long
098        long sleepDuration = SLEEP_DURATION;
099        for (int i = 0; i < NB_TRY; i++) {
100            if (kvStore.compareAndSet(key, null, LOCK)) {
101                return true;
102            }
103            Thread.sleep(sleepDuration);
104            sleepDuration *= 2;
105        }
106        return false;
107    }
108
109    protected static void unlock(String key, KeyValueStore kvStore) {
110        kvStore.put(key, (String) null);
111    }
112
113}