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

io.sirix.cache.RedBlackTreeNodeCache Maven / Gradle / Ivy

package io.sirix.cache;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.RemovalCause;
import com.github.benmanes.caffeine.cache.RemovalListener;
import io.sirix.index.redblacktree.RBNodeKey;
import io.sirix.node.interfaces.Node;
import org.checkerframework.checker.nullness.qual.NonNull;

import java.util.Map;

public final class RedBlackTreeNodeCache implements Cache {

  private final com.github.benmanes.caffeine.cache.Cache cache;

  public RedBlackTreeNodeCache(final int maxSize) {
    final RemovalListener removalListener =
        (RBIndexKey key, Node value, RemovalCause cause) -> {
          assert key != null;
          assert value != null;

          if (value instanceof RBNodeKey rbNodeKey) {
            final RBNodeKey parent = rbNodeKey.getParent();

            if (parent != null) {
              if (value.equals(parent.getLeftChild())) {
                parent.setLeftChild(null);
              } else if (value.equals(parent.getRightChild())) {
                parent.setRightChild(null);
              }
            }
          }
        };

    cache = Caffeine.newBuilder().maximumSize(maxSize).removalListener(removalListener).scheduler(scheduler).build();
  }

  @Override
  public void clear() {
    cache.invalidateAll();
  }

  @Override
  public Node get(RBIndexKey key) {
    return cache.getIfPresent(key);
  }

  @Override
  public void put(RBIndexKey key, @NonNull Node value) {
    cache.put(key, value);
  }

  @Override
  public void putAll(Map map) {
    cache.putAll(map);
  }

  @Override
  public void toSecondCache() {
    throw new UnsupportedOperationException();
  }

  @Override
  public Map getAll(Iterable keys) {
    return cache.getAllPresent(keys);
  }

  @Override
  public void remove(RBIndexKey key) {
    cache.invalidate(key);
  }

  @Override
  public void close() {
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy