All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.spring.boxes.redis.lock.support.AbstractLockTemplate Maven / Gradle / Ivy

The newest version!
package com.spring.boxes.redis.lock.support;

import com.spring.boxes.redis.lock.LockAction;
import com.spring.boxes.redis.lock.LockResult;
import com.spring.boxes.redis.lock.LockTemplate;

import java.util.concurrent.TimeUnit;

public abstract class AbstractLockTemplate implements LockTemplate {

    public static final long _30_SECONDS = TimeUnit.SECONDS.toMillis(30);
    public static final long _30_MINUTES = TimeUnit.MINUTES.toMillis(60);

    @Override
    public boolean tryLock(String lockKey) {
        return tryLock(lockKey, _30_SECONDS, _30_MINUTES);
    }

    @Override
    public boolean tryLock(String lockKey, long waitTime) {
        return tryLock(lockKey, waitTime, _30_MINUTES);
    }

    @Override
    public  LockResult execute(String lockKey, LockAction lockAction) {
        return execute(lockKey, _30_SECONDS, _30_MINUTES, lockAction);
    }

    @Override
    public  LockResult execute(String lockKey, long waitTime, LockAction lockAction) {
        return execute(lockKey, waitTime, _30_MINUTES, lockAction);
    }

    @Override
    public  LockResult execute(String lockKey, long waitTime, long leaseTime, LockAction lockAction) {
        SimpleLockResult lockResult = new SimpleLockResult<>();
        T returnValue;
        try {
            boolean success = tryLock(lockKey, waitTime, leaseTime);
            lockResult.setSuccess(success);
            if (!lockResult.isSuccess()) {
                return lockResult;
            }
            try {
                returnValue = lockAction.doInLock();
            } catch (Throwable e) {
                String error = String.format("DO LOCK ACTION FAILED: key=%s||tryLockTime=%s||lockExpiredTime=%s", lockKey, waitTime, leaseTime);
                throw new IllegalStateException(error, e);
            }
            lockResult.setReturnValue(returnValue);
            return lockResult;
        } finally {
            if (lockResult.isSuccess()) {
                unlock(lockKey);
            }
        }
    }


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy