我得到了一个代码,它根据用户名和服务类型创建一个唯一的 ID。唯一 ID 在 db 中,通过我看不到的 DAO 类读取 db。创建 id 需要很多步骤。
create(user,service) {
id=getIdViaDAO(user,service)
if(id==null) {
create few classes and call few methods.
id=generareId(few objects)
session.setId(id)
dao.createSession(session)
}
return id
}
在多线程环境中,无法保证唯一 ID。
保证唯一性
解决方案:我会将 id 缓存在 ConcurrentHashmap 中,其中 userId+service 作为键,id 作为值。每当调用该方法时,我将检查 value(id) 如果不存在密钥上的锁并创建 id。这将减少争用并保证唯一性。
想知道我的解决方案是否有任何问题和/或是否有更好的解决方案?