Java: Synchronizing on primitives?

前端 未结 10 1964
小鲜肉
小鲜肉 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条回答
  •  Happy的楠姐
    2021-02-01 22:02

    You could create a list or set of active ids and use wait and notify:

    List working;
    public void doWork(long id) {
    synchronized(working)
    {
       while(working.contains(id))
       {
          working.wait();
       }
       working.add(id)//lock
    }
    //do something
    synchronized(working)
    {
        working.remove(id);//unlock
        working.notifyAll();
    }
    }
    

    Problems solved:

    • Only threads with same id's wait, all others are concurrent
    • No memory Leak as the "locks" (Long) will be removed on unlock
    • Works with autoboxing

    Problems there:

    • while/notifyAll may cause some performance loss with high number of threads
    • Not reentrant

提交回复
热议问题