广州营销网站建设公司哪家好,信息技术网站开发,网站开发用什么语言比较好,wordpress 首页评论单例模式#xff08;3#xff09;
实现集群环境下的分布式单例类
如何理解单例模式中的唯一性#xff1f;
单例模式创建的对象是进程唯一的。以springboot应用程序为例#xff0c;他是一个进程#xff0c;可能包含多个线程#xff0c;单例代表在这个进程的某个类是唯一…单例模式3
实现集群环境下的分布式单例类
如何理解单例模式中的唯一性
单例模式创建的对象是进程唯一的。以springboot应用程序为例他是一个进程可能包含多个线程单例代表在这个进程的某个类是唯一的在不同的线程中类是相同的。
如何实现线程唯一的单例
/*** 线程中的单例*/
public class ThreadIdGenrator {private static final MapLong, ThreadIdGenrator map new ConcurrentHashMap();private AtomicInteger id new AtomicInteger(0);public static ThreadIdGenrator getInstance() {long threadId Thread.currentThread().getId();ThreadIdGenrator threadIdGenrator map.putIfAbsent(threadId, new ThreadIdGenrator());return threadIdGenrator;}public int nextInt() {return id.incrementAndGet();}
}如何实现集群环境下的单例 我们需要把这个单例对象序列化并存储到外部共享存储区比如文件。进程在使用这个单例对象的时候需要先从外部共享存储区中将它读取到内存并反序列化成对象然后再使用使用完成之后还需要再存储回外部共享存储区。 为了保证任何时刻在进程间都只有一份对象存在一个进程在获取到对象之后需要对对象加锁避免其他进程再将其获取。在进程使用完这个对象之后还需要显式地将对象从内存中删除并且释放对对象的加锁。 问题这里为什么要加锁 理由如果多个进程读取同一份序列化文件得到的对象的地址是不一样的这样子就无法保证全局的唯一性序列化后的对象与原对象只是值相等但是对象的地址是不相等的为了保证全局的唯一性必须保证在集群下在使用单例对象时需要加锁当多线程使用时只有一个线程可以使用成功其他线程必须阻塞
import java.util.concurrent.atomic.AtomicLong;public class IdGenerator {private AtomicLong id new AtomicLong(0);private static IdGenerator instance;private static SharedObjectStorage storage FileSharedObjectStorage(/* 入参省略 */);private static DistributedLock lock new DistributedLock();private IdGenerator() {}public static IdGenerator getInstance() {if (instance null) {lock.lock();instance storage.load(IdGenerator.class);lock.unlock(); // 放置于try-finally块内确保解锁}return instance;}public void freeInstance() {lock.lock();try {storage.save(this, IdGenerator.class);instance null; // 释放对象} finally {lock.unlock();}}public long getId() {return id.incrementAndGet();}
}
如何实现一个多例模式
多例的理解 “多例”指的就是一个类可以创建多个对象但是个数是有限制的同一类型的只能创建一个对象不同类型的可以创建多个对象 类型同一个 name 获取到的对象实例是相同的以ID生成器为例我希望在用户注册时使用的是一个ID生成器在增加商品时使用的是另一个ID生成器即根据场景划分使用不同的ID生成器
public class DuoLiIdGenertor {private static final MapString, DuoLiIdGenertor map new ConcurrentHashMap();private AtomicInteger id new AtomicInteger(0);public static DuoLiIdGenertor getInstance(String name) {map.putIfAbsent(name, new DuoLiIdGenertor());return map.get(name);}public int nextInt() {return id.incrementAndGet();}}public static void main(String[] args) {DuoLiIdGenertor user getInstance(user);DuoLiIdGenertor goods getInstance(goods);DuoLiIdGenertor user1 getInstance(user);System.out.println(user.hashCode());System.out.println(goods.hashCode());System.out.println(user1.hashCode());}