Java: Synchronizing on primitives?

前端 未结 10 1825
小鲜肉
小鲜肉 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:01

    I'd say you're already pretty far to having a solution. Make a LockManager who lazily and reference-counted-ly manages those locks for you. Then use it in doWork:

    public void doWork(long id) {
        LockObject lock = lockManager.GetMonitor(id);
        try {
            synchronized(lock) {
                // ...
            }
        } finally {
            lock.Release();
        }
    }
    

提交回复
热议问题