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

com.github.yizzuide.milkomeda.light.SortDiscard Maven / Gradle / Ivy

/*
 * Copyright (c) 2021 yizzuide All rights Reserved.
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.github.yizzuide.milkomeda.light;

import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * SortDiscard
 *
 * 抽象的字段排序方案
 *
 * @since 1.8.0
 * @version 3.12.10
 * @author yizzuide
 * 
* Create at 2019/06/28 16:32 */ @Slf4j public abstract class SortDiscard implements Discard { @Override @SuppressWarnings("unchecked") public Spot deform(String key, Spot spot, long expire) { SortSpot sortSpot = null; try { sortSpot = spotClazz().newInstance(); sortSpot.setView(spot.getView()); sortSpot.setData(spot.getData()); sortSpot.setKey(key); } catch (Exception e) { log.error("SortDiscard:- 创建类实例失败:{}", e.getMessage(), e); } return sortSpot; } @Override @SuppressWarnings("unchecked") public void discard(Map> cacheMap, float l1DiscardPercent) { Comparator> comparator = comparator(); // 不支持排序丢弃,直接返回 if (comparator == null) { return; } List> list = cacheMap.values() .stream() .map(spot -> (SortSpot)spot) .sorted((Comparator>) comparator) .collect(Collectors.toList()); int size = list.size(); int discardCount = Math.round(size * l1DiscardPercent); // 一级缓存百分比太小,直接返回 if (discardCount == 0) { return; } if (discardCount >= size) { discardCount = size - 1; } Map> newCacheMap = new HashMap<>(size); for (int i = discardCount; i < size; i++) { String key = list.get(i).getKey(); newCacheMap.put(key, cacheMap.get(key)); } cacheMap.clear(); cacheMap.putAll(newCacheMap); } /** * 排序比较器 * @return Comparator */ protected abstract Comparator> comparator(); }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy