每日JAVA知识3.20

目录

资深的 Java 项目代码:分布式缓存系统模拟

代码示例

代码说明

改进方案

改进代码(缓存持久化)

2. 常见的 Java 语法介绍

2.1 Java 中的 CompletableFuture

代码说明

改进方案

改进代码

改进代码说明

2.2 Java 中的 VarHandle

代码说明

改进方案

改进代码

改进代码说明

3. 常见的错误及解决办法

3.1 RejectedExecutionException(拒绝执行异常)

代码说明

解决办法

改进代码

改进代码说明

3.2 ClassCastException(类转换异常)

代码说明

解决办法

改进代码

改进代码说明


资深的 Java 项目代码:分布式缓存系统模拟

代码示例

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

// 缓存项类
class CacheItem {
    private Object value;
    private long expirationTime;

    public CacheItem(Object value, long expirationTime) {
        this.value = value;
        this.expirationTime = expirationTime;
    }

    public Object getValue() {
        return value;
    }

    public boolean isExpired() {
        return System.currentTimeMillis() > expirationTime;
    }
}

// 分布式缓存节点类
class DistributedCacheNode {
    private final String nodeId;
    private final ConcurrentHashMap<String, CacheItem> cache;
    private final ScheduledExecutorService cleaner;
    private final ReentrantLock lock = new ReentrantLock();

    public DistributedCacheNode(String nodeId) {
        this.nodeId = nodeId;
        this.cache = new ConcurrentHashMap<>();
        this.cleaner = Executors.newSingleThreadScheduledExecutor();
        // 每隔 10 秒清理一次过期缓存项
        cleaner.scheduleAtFixedRate(this::cleanExpiredItems, 10, 10, TimeUnit.SECONDS);
    }

    public String getNodeId() {
        return nodeId;
    }

    public void put(String key, Object value, long expirationSeconds) {
        lock.lock();
        try {
            long expirationTime = System.currentTimeMillis() + expirationSeconds * 1000;
            cache.put(key, new CacheItem(value, expirationTime));
        } finally {
            lock.unlock();
        }
    }

    public Object get(String key) {
        lock.lock();
        try {
            CacheItem item = cache.get(key);
            if (item != null &&!item.isExpired()) {
                return item.getValue();
            } else if (item != null) {
                cache.remove(key);
            }
            return null;
        } finally {
            lock.unlock();
        }
    }

    public void remove(String key) {
        lock.lock();
        try {
            cache.remove(key);
        } finally {
            lock.unlock();
        }
    }

    private void cleanExpiredItems() {
        lock.lock();
        try {
            Iterator<Map.Entry<String, CacheItem>> iterator = cache.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, CacheItem> entry = iterator.next();
                if (entry.getValue().isExpired()) {
                    iterator.remove();
                }
            }
        } finally {
            lock.unlock();
        }
    }

    public void shutdown() {
        cleaner.shutdownNow();
    }
}

// 分布式缓存系统类
class DistributedCacheSystem {
    private final List<DistributedCacheNode> nodes;
    private final ConsistentHashing hashing;

    public DistributedCacheSystem(int nodeCount) {
        this.nodes = new ArrayList<>();
        for (int i = 0; i < nodeCount; i++) {
            DistributedCacheNode node = new DistributedCacheNode("Node-" + i);
            nodes.add(node);
        }
        this.hashing = new ConsistentHashing(nodes);
    }

    public void put(String key, Object value, long expirationSeconds) {
        DistributedCacheNode node = hashing.getNode(key);
        node.put(key, value, expirationSeconds);
    }

    public Object get(String key) {
        DistributedCacheNode node = hashing.getNode(key);
        return node.get(key);
    }

    public void remove(String key) {
        DistributedCacheNode node = hashing.getNode(key);
        node.remove(key);
    }

    public void shutdown() {
        for (DistributedCacheNode node : nodes) {
            node.shutdown();
        }
    }
}

// 一致性哈希类
class ConsistentHashing {
    private final TreeMap<Long, DistributedCacheNode> circle = new TreeMap<>();
    private static final int VIRTUAL_NODES = 100;

    public ConsistentHashing(List<DistributedCacheNode> nodes) {
        for (DistributedCacheNode node : nodes) {
            for (int i = 0; i < VIRTUAL_NODES; i++) {
                String virtualNodeName = node.getNodeId() + "-VN" + i;
                long hash = hash(virtualNodeName);
                circle.put(hash, node);
            }
        }
    }

    public DistributedCacheNode getNode(String key) {
        if (circle.isEmpty()) {
            return null;
        }
        long hash = hash(key);
        if (!circle.containsKey(hash)) {
            SortedMap<Long, DistributedCacheNode> tailMap = circle.tailMap(hash);
            hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
        }
        return circle.get(hash);
    }

    private long hash(String key) {
        // 简单的哈希函数示例
        long hash = 0;
        for (int i = 0; i < key.length(); i++) {
            hash = (hash * 31) + key.charAt(i);
        }
        return hash;
    }
}

// 主类,用于测试分布式缓存系统
public class DistributedCacheTest {
    public static void main(String[] args) {
        DistributedCacheSystem cacheSystem = new DistributedCacheSystem(3);

        cacheSystem.put("key1", "value1", 60);
        cacheSystem.put("key2", "value2", 120);

        Object value1 = cacheSystem.get("key1");
        System.out.println("key1 的值: " + value1);

        cacheSystem.remove("key1");
        Object removedValue = cacheSystem.get("key1");
        System.out.println("删除 key1 后的值: " + removedValue);

        cacheSystem.shutdown();
    }
}
代码说明

  • CacheItem 类
    • 表示缓存中的一个项,包含值和过期时间。
    • isExpired 方法用于检查缓存项是否已过期。
  • DistributedCacheNode 类
    • 代表分布式缓存系统中的一个节点,使用 ConcurrentHashMap 存储缓存项。
    • put 方法用于向缓存中添加项,并设置过期时间。
    • get 方法用于从缓存中获取项,如果项已过期则移除。
    • remove 方法用于从缓存中移除项。
    • cleanExpir
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萧十一郎@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值