开发者

Java Synchronization with db values

I was given a code, it creates a unique id based on the user name and the service type. The unique id is in db , db is read via DAO classes which i cant see. it takes lot of steps to create the 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
}

On a multi threaded environmen开发者_开发百科t, there is no guarantee for unique id.

To guarantee the uniqueness

Solution: I would cache the id in a ConcurrentHashmap with userId+service as key and id as value. Whenever the method is called i will check for the value(id) if not present lock on the key and create the id. This will reduce the contention and guarantee the uniqueness.

Wondering if there is any issue in my solution and / or is there a better solution for this?


the same user and service should give you the same ID, so you're good. A couple of things to watch out for:

  • make sure user id and service implement hashCode() and equals() properly
  • make sure to have a synchronized() lock around the entire create() method
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜