Java: Synchronizing on primitives?

前端 未结 10 1947
小鲜肉
小鲜肉 2021-02-01 21:13

In our system, we have a method that will do some work when it\'s called with a certain ID:

public void doWork(long id) { /* ... */ }

Now, this

10条回答
  •  野性不改
    2021-02-01 22:11

    This is where I would use a canonicalizing map, which takes your long input and returns a canonical Long object that you can then use to synchronize. I've written about canonicalizing maps here; simply replace String by Long (and to make your life easier, let it take a long as a parameter).

    Once you have the canonicalizing map, you'd write your lock-guarded code like this:

    Long lockObject = canonMap.get(id);
    synchronized (lockObject)
    {
        // stuff
    }
    

    The canonicalizing map would ensure that the same lockObject is returned for the same ID. When there are no active references to lockObject, they will be eligible for garbage collection, so you won't fill up memory with needless objects.

提交回复
热议问题