org.apache.flink.runtime.state.gemini.engine.vm.DataPageLRU Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.flink.runtime.state.gemini.engine.vm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* LogicPageLRU. when Page load from File, and still not enter into Cache. then this page will be put in this small LRU.
* no thread safe.
*/
public class DataPageLRU extends LinkedHashMap {
private static final Logger LOG = LoggerFactory.getLogger(DataPageLRU.class);
private final long lruSize;
private final DataPageLRUFuction function;
private volatile int totalSize = 0;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
public DataPageLRU(long lruSize, DataPageLRUFuction function) {
this.lruSize = lruSize;
this.function = function;
}
public int getTotalSize() {
return totalSize;
}
@Override
public V put(K key, V value) {
lock.writeLock().lock();
V result;
try {
result = super.put(key, value);
totalSize += function.size(value);
if (result != null) {
totalSize -= function.size(result);
function.removed(result);
}
} finally {
lock.writeLock().unlock();
}
return result;
}
@Override
public V get(Object key) {
lock.readLock().lock();
try {
return super.get(key);
} finally {
lock.readLock().unlock();
}
}
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
if (size() > this.lruSize) {
totalSize -= function.size(eldest.getValue());
function.removed(eldest.getValue());
return true;
}
return super.removeEldestEntry(eldest);
}
/**
* SizeAble.
*/
public interface DataPageLRUFuction {
int size(T value);
void removed(T value);
}
}