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

org.redisson.transaction.BaseTransactionalSet Maven / Gradle / Ivy

Go to download

Easy Redis Java client and Real-Time Data Platform. Valkey compatible. Sync/Async/RxJava3/Reactive API. Client side caching. Over 50 Redis based Java objects and services: JCache API, Apache Tomcat, Hibernate, Spring, Set, Multimap, SortedSet, Map, List, Queue, Deque, Semaphore, Lock, AtomicLong, Map Reduce, Bloom filter, Scheduler, RPC

There is a newer version: 3.43.0
Show newest version
/**
 * Copyright (c) 2013-2021 Nikita Koksharov
 *
 * 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 org.redisson.transaction;

import io.netty.buffer.ByteBuf;
import org.redisson.RedissonMultiLock;
import org.redisson.RedissonObject;
import org.redisson.RedissonSet;
import org.redisson.ScanResult;
import org.redisson.api.*;
import org.redisson.client.RedisClient;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.misc.Hash;
import org.redisson.misc.HashValue;
import org.redisson.misc.RPromise;
import org.redisson.misc.RedissonPromise;
import org.redisson.transaction.operation.DeleteOperation;
import org.redisson.transaction.operation.TouchOperation;
import org.redisson.transaction.operation.TransactionalOperation;
import org.redisson.transaction.operation.UnlinkOperation;
import org.redisson.transaction.operation.set.MoveOperation;

import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

/**
 * 
 * @author Nikita Koksharov
 *
 * @param  value type
 */
public abstract class BaseTransactionalSet extends BaseTransactionalObject {

    static final Object NULL = new Object();
    
    private final long timeout;
    final Map state = new HashMap();
    final List operations;
    final RCollectionAsync set;
    final RObject object;
    final String name;
    final CommandAsyncExecutor commandExecutor;
    Boolean deleted;
    
    public BaseTransactionalSet(CommandAsyncExecutor commandExecutor, long timeout, List operations, RCollectionAsync set) {
        this.commandExecutor = commandExecutor;
        this.timeout = timeout;
        this.operations = operations;
        this.set = set;
        this.object = (RObject) set;
        this.name = object.getName();
    }

    private HashValue toHash(Object value) {
        ByteBuf state = ((RedissonObject) set).encode(value);
        try {
            return new HashValue(Hash.hash128(state));
        } finally {
            state.release();
        }
    }
    
    public RFuture isExistsAsync() {
        if (deleted != null) {
            return RedissonPromise.newSucceededFuture(!deleted);
        }
        
        return set.isExistsAsync();
    }
    
    public RFuture unlinkAsync(CommandAsyncExecutor commandExecutor) {
        return deleteAsync(commandExecutor, new UnlinkOperation(name));
    }
    
    public RFuture touchAsync(CommandAsyncExecutor commandExecutor) {
        RPromise result = new RedissonPromise();
        if (deleted != null && deleted) {
            operations.add(new TouchOperation(name));
            result.trySuccess(false);
            return result;
        }
        
        set.isExistsAsync().onComplete((exists, e) -> {
            if (e != null) {
                result.tryFailure(e);
                return;
            }
            
            operations.add(new TouchOperation(name));
            if (!exists) {
                for (Object value : state.values()) {
                    if (value != NULL) {
                        exists = true;
                        break;
                    }
                }
            }
            result.trySuccess(exists);
        });
                
        return result;
    }

    public RFuture deleteAsync(CommandAsyncExecutor commandExecutor) {
        return deleteAsync(commandExecutor, new DeleteOperation(name));
    }

    protected RFuture deleteAsync(CommandAsyncExecutor commandExecutor, TransactionalOperation operation) {
        RPromise result = new RedissonPromise();
        if (deleted != null) {
            operations.add(operation);
            result.trySuccess(!deleted);
            deleted = true;
            return result;
        }
        
        set.isExistsAsync().onComplete((res, e) -> {
            if (e != null) {
                result.tryFailure(e);
                return;
            }
            
            operations.add(operation);
            state.replaceAll((k, v) -> NULL);
            deleted = true;
            result.trySuccess(res);
        });
        return result;
    }
    
    public RFuture containsAsync(Object value) {
        for (Object val : state.values()) {
            if (val != NULL && isEqual(val, value)) {
                return RedissonPromise.newSucceededFuture(true);
            }
        }
        
        return set.containsAsync(value);
    }
    
    protected abstract ScanResult scanIteratorSource(String name, RedisClient client,
                                                             long startPos, String pattern, int count);
    
    protected ScanResult scanIterator(String name, RedisClient client,
            long startPos, String pattern, int count) {
        ScanResult res = scanIteratorSource(name, client, startPos, pattern, count);
        Map newstate = new HashMap<>(state);
        for (Iterator iterator = res.getValues().iterator(); iterator.hasNext();) {
            Object entry = iterator.next();
            Object value = newstate.remove(toHash(entry));
            if (value == NULL) {
                iterator.remove();
            }
        }
        
        if (startPos == 0) {
            for (Entry entry : newstate.entrySet()) {
                if (entry.getValue() == NULL) {
                    continue;
                }
                res.getValues().add(entry.getValue());
            }
        }
        
        return res;
    }
    
    protected abstract RFuture> readAllAsyncSource();
    
    public RFuture> readAllAsync() {
        RPromise> result = new RedissonPromise<>();
        RFuture> future = readAllAsyncSource();
        future.onComplete((res, e) -> {
            if (e != null) {
                result.tryFailure(e);
                return;
            }
            
            Map newstate = new HashMap<>(state);
            for (Iterator iterator = res.iterator(); iterator.hasNext();) {
                V key = iterator.next();
                Object value = newstate.remove(toHash(key));
                if (value == NULL) {
                    iterator.remove();
                }
            }
            
            for (Object value : newstate.values()) {
                if (value == NULL) {
                    continue;
                }
                res.add((V) value);
            }
            
            result.trySuccess(res);
        });

        return result;
    }
    
    public RFuture addAsync(V value) {
        long threadId = Thread.currentThread().getId();
        TransactionalOperation operation = createAddOperation(value, threadId);
        return addAsync(value, operation);
    }
    
    public RFuture addAsync(V value, TransactionalOperation operation) {
        RPromise result = new RedissonPromise<>();
        executeLocked(result, value, new Runnable() {
            @Override
            public void run() {
                HashValue keyHash = toHash(value);
                Object entry = state.get(keyHash);
                if (entry != null) {
                    operations.add(operation);
                    state.put(keyHash, value);
                    if (deleted != null) {
                        deleted = false;
                    }
                    
                    result.trySuccess(entry == NULL);
                    return;
                }
                
                set.containsAsync(value).onComplete((res, e) -> {
                    if (e != null) {
                        result.tryFailure(e);
                        return;
                    }
                    
                    operations.add(operation);
                    state.put(keyHash, value);
                    if (deleted != null) {
                        deleted = false;
                    }
                    result.trySuccess(!res);
                });
            }
        });
        return result;
    }

    protected abstract TransactionalOperation createAddOperation(V value, long threadId);
    
    public RFuture removeRandomAsync() {
        throw new UnsupportedOperationException();
    }
    
    public RFuture> removeRandomAsync(int amount) {
        throw new UnsupportedOperationException();
    }
    
    public RFuture moveAsync(String destination, V value) {
        RSet destinationSet = new RedissonSet(object.getCodec(), commandExecutor, destination, null);
        
        RPromise result = new RedissonPromise();
        RLock destinationLock = getLock(destinationSet, value);
        RLock lock = getLock(set, value);
        RedissonMultiLock multiLock = new RedissonMultiLock(destinationLock, lock);
        long threadId = Thread.currentThread().getId();
        multiLock.lockAsync(timeout, TimeUnit.MILLISECONDS).onComplete((res, e) -> {
            if (e != null) {
                multiLock.unlockAsync(threadId);
                result.tryFailure(e);
                return;
            }
            
            HashValue keyHash = toHash(value);
            Object currentValue = state.get(keyHash);
            if (currentValue != null) {
                operations.add(createMoveOperation(destination, value, threadId));
                if (currentValue == NULL) {
                    result.trySuccess(false);
                } else {
                    state.put(keyHash, NULL);
                    result.trySuccess(true);
                }
                return;
            }
            
            set.containsAsync(value).onComplete((r, ex) -> {
                if (ex != null) {
                    result.tryFailure(ex);
                    return;
                }
                
                operations.add(createMoveOperation(destination, value, threadId));
                if (r) {
                    state.put(keyHash, NULL);
                }

                result.trySuccess(r);
            });
        });
        
        return result;
    }

    protected abstract MoveOperation createMoveOperation(String destination, V value, long threadId);

    protected abstract RLock getLock(RCollectionAsync set, V value);
    
    public RFuture removeAsync(Object value) {
        RPromise result = new RedissonPromise();
        long threadId = Thread.currentThread().getId();
        executeLocked(result, (V) value, new Runnable() {
            @Override
            public void run() {
                HashValue keyHash = toHash(value);
                Object currentValue = state.get(keyHash);
                if (currentValue != null) {
                    operations.add(createRemoveOperation(value, threadId));
                    if (currentValue == NULL) {
                        result.trySuccess(false);
                    } else {
                        state.put(keyHash, NULL);
                        result.trySuccess(true);
                    }
                    return;
                }

                set.containsAsync(value).onComplete((res, e) -> {
                    if (e != null) {
                        result.tryFailure(e);
                        return;
                    }
                    
                    operations.add(createRemoveOperation(value, threadId));
                    if (res) {
                        state.put(keyHash, NULL);
                    }

                    result.trySuccess(res);
                });
            }

        });
        return result;
        
    }

    protected abstract TransactionalOperation createRemoveOperation(Object value, long threadId);
    
    public RFuture containsAllAsync(Collection c) {
        List coll = new ArrayList(c);
        for (Iterator iterator = coll.iterator(); iterator.hasNext();) {
            Object value = iterator.next();
            for (Object val : state.values()) {
                if (val != NULL && isEqual(val, value)) {
                    iterator.remove();
                    break;
                }
            }
        }
        
        return set.containsAllAsync(coll);
    }

    public RFuture addAllAsync(Collection c) {
        RPromise result = new RedissonPromise();
        long threadId = Thread.currentThread().getId();
        executeLocked(result, new Runnable() {
            @Override
            public void run() {
                containsAllAsync(c).onComplete((res, e) -> {
                    if (e != null) {
                        result.tryFailure(e);
                        return;
                    }

                    for (V value : c) {
                        operations.add(createAddOperation(value, threadId));
                        HashValue keyHash = toHash(value);
                        state.put(keyHash, value);
                    }
                    
                    if (deleted != null) {
                        deleted = false;
                    }
                    
                    result.trySuccess(!res);
                });
            }
        }, c);
        return result;
    }
    
    public RFuture retainAllAsync(Collection c) {
        throw new UnsupportedOperationException();
    }
    
    public RFuture removeAllAsync(Collection c) {
        RPromise result = new RedissonPromise();
        long threadId = Thread.currentThread().getId();
        executeLocked(result, new Runnable() {
            @Override
            public void run() {
                containsAllAsync(c).onComplete((res, e) -> {
                    if (e != null) {
                        result.tryFailure(e);
                        return;
                    }

                    for (Object value : c) {
                        operations.add(createRemoveOperation(value, threadId));
                        HashValue keyHash = toHash(value);
                        state.put(keyHash, NULL);
                    }
                    
                    result.trySuccess(!res);
                });
            }
        }, c);
        return result;
    }
    
    public RFuture unionAsync(String... names) {
        throw new UnsupportedOperationException();
    }
    
    public RFuture diffAsync(String... names) {
        throw new UnsupportedOperationException();
    }
    
    public RFuture intersectionAsync(String... names) {
        throw new UnsupportedOperationException();
    }
    
    public RFuture> readSortAsync(SortOrder order) {
        throw new UnsupportedOperationException();
    }
    
    public RFuture> readSortAsync(SortOrder order, int offset, int count) {
        throw new UnsupportedOperationException();
    }
    
    public RFuture> readSortAsync(String byPattern, SortOrder order) {
        throw new UnsupportedOperationException();
    }

    public  RFuture> readSortAsync(String byPattern, List getPatterns, SortOrder order, int offset, int count) {
        throw new UnsupportedOperationException();
    }

    public RFuture> readSortAlphaAsync(SortOrder order) {
        throw new UnsupportedOperationException();
    }

    public RFuture> readSortAlphaAsync(SortOrder order, int offset, int count) {
        throw new UnsupportedOperationException();
    }

    public RFuture>  readSortAlphaAsync(String byPattern, SortOrder order) {
        throw new UnsupportedOperationException();
    }

    public RFuture>  readSortAlphaAsync(String byPattern, SortOrder order, int offset, int count) {
        throw new UnsupportedOperationException();
    }

    public  RFuture> readSortAlphaAsync(String byPattern, List getPatterns, SortOrder order) {
        throw new UnsupportedOperationException();
    }

    public  RFuture> readSortAlphaAsync(String byPattern, List getPatterns, SortOrder order, int offset, int count) {
        throw new UnsupportedOperationException();
    }

    public RFuture sortToAsync(String destName, String byPattern, List getPatterns, SortOrder order, int offset, int count) {
        throw new UnsupportedOperationException();
    }

    public RFuture> readUnionAsync(String... names) {
        throw new UnsupportedOperationException();
    }
    
    public RFuture> readDiffAsync(String... names) {
        throw new UnsupportedOperationException();
    }
    
    public RFuture> readIntersectionAsync(String... names) {
        throw new UnsupportedOperationException();
    }
    
    private boolean isEqual(Object value, Object oldValue) {
        ByteBuf valueBuf = ((RedissonObject) set).encode(value);
        ByteBuf oldValueBuf = ((RedissonObject) set).encode(oldValue);
        
        try {
            return valueBuf.equals(oldValueBuf);
        } finally {
            valueBuf.readableBytes();
            oldValueBuf.readableBytes();
        }
    }
    
    protected  void executeLocked(RPromise promise, Object value, Runnable runnable) {
        RLock lock = getLock(set, (V) value);
        executeLocked(promise, runnable, lock);
    }

    protected  void executeLocked(RPromise promise, Runnable runnable, RLock lock) {
        lock.lockAsync(timeout, TimeUnit.MILLISECONDS).onComplete((res, e) -> {
            if (e == null) {
                runnable.run();
            } else {
                promise.tryFailure(e);
            }
        });
    }
    
    protected  void executeLocked(RPromise promise, Runnable runnable, Collection values) {
        List locks = new ArrayList(values.size());
        for (Object value : values) {
            RLock lock = getLock(set, (V) value);
            locks.add(lock);
        }
        RedissonMultiLock multiLock = new RedissonMultiLock(locks.toArray(new RLock[locks.size()]));
        long threadId = Thread.currentThread().getId();
        multiLock.lockAsync(timeout, TimeUnit.MILLISECONDS).onComplete((res, e) -> {
            if (e == null) {
                runnable.run();
            } else {
                multiLock.unlockAsync(threadId);
                promise.tryFailure(e);
            }
        });
    }
    
}