Java: Synchronizing on primitives?

前端 未结 10 1845
小鲜肉
小鲜肉 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 21:50

    You can try the following little 'hack'

    String str = UNIQUE_METHOD_PREFIX + Long.toString(id);
    synchornized(str.intern()) { .. }
    

    which is 100% guaranteed to return the same instance.

    The UNIQUE_METHOD_PREFIX, may be a hardcoded constant, or may be obtained using:

    StackTraceElement ste = Thread.currentThread().getStackTrace()[0];
    String uniquePrefix = ste.getDeclaringClass() + ":" +ste.getMethodName();
    

    which will guarantee that the lock happens only on this precise method. That's in order to avoid deadlocks.

提交回复
热议问题