Ensure Java synchronized locks are taken in order?

2019-01-09 13:04发布

we have two threads accessing one list via a synchronized method. Can we

a) rely on the run time to make sure that each of them will receive access to the method based on the order they tried to or

b) does the VM follow any other rules

c) is there a better way to serialize the requests?

6条回答
狗以群分
2楼-- · 2019-01-09 13:25

You can't rely on the order in which the particular method is called from each threads. If it is only two threads may be yes. But imagine if there are 3 threads and 1 thread already acquired access. The other 2 threads when they try to access will wait and any one of them can be awarded the access, and this does not depend on the order in which they called this method. So, it is not suggested to rely on the order.

查看更多
混吃等死
3楼-- · 2019-01-09 13:26

c) is there a better way to serialize the requests?

Are you by any chance using the list as a queue, i.e., does the usage pattern look something like this?

while (some condition) {
    synchronized(theList){
        anItem = get and remove an element from theList
    }
    do some work with anItem
}

If so, you may want to look at the BlockingQueue interface instead of using your own locking schemes. The implementations (like ArrayBlockingQueue) have settings for fairness and more.

查看更多
贪生不怕死
4楼-- · 2019-01-09 13:28

No you cannot be sure that two calls to a synchronized method will occur in order. The order is unspecified and implementation dependent.

This is defined in the 17.1 Locks section of the JLS. Notice that is says nothing about the order in which threads waiting on a lock should gain access.

查看更多
淡お忘
5楼-- · 2019-01-09 13:38

No, synchronized will give access in any order (Depends on the JVM implementation). This could even cause Threads to starve in some scenarios.

You can ensure the order by using ReentrantLock (since Java 5.0) with the fair=true option. (Lock lock = new ReentrantLock(true);)

查看更多
爷的心禁止访问
6楼-- · 2019-01-09 13:52

I always leave syncs to app server or engine unless defining own intensity

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-09 13:52

Yes.

If access to the list is via one synchronized method, concurrent requests from multiple threads will be serialized.

查看更多
登录 后发表回答