Java Sync - Mutex.wait and List.wait

When using Java Threading primitives to build a thread safe queue - what is the difference between the two constructs?

  • Create an explicit lock object.
  • Using a list as a lock and waiting on it.

Example 1

private final Object lock = new Object(); private ArrayList<String> list = new ArrayList<String>(); public String dequeue() { synchronized (lock) { while (list.size() == 0) { lock.wait(); } String value = list.remove(0); lock.notifyAll(); return value; } } public void enqueue(String value) { synchronized (lock) { while (list.size() == maxSize) { lock.wait(); } list.add(value); lock.notifyAll(); } } 

Example 2

 private ArrayList<String> list = new ArrayList<String>(); public String dequeue() { synchronized (list) { // lock on list while (list.size() == 0) { list.wait(); // wait on list } String value = list.remove(0); list.notifyAll(); return value; } } public void enqueue(String value) { synchronized (list) { // lock on list while (list.size() == maxSize) { list.wait(); // wait on list } list.add(value); list.notifyAll(); } } 

Note

  • This is a limited list.
  • No other operation is performed out of turn and dequeue.
  • I could use a blocking queue, but this question is more suitable for improving my limited knowledge of threads.
  • If this question is repeated, please let me know.
+4
source share
1 answer

Short answer: no, there is no functional difference, except for the extra unnecessary memory overhead for saving this additional lock object. However, there are several semantics-related elements that I would like to consider before making a final decision.

Will I ever have to perform synchronized operations more than just my internal list?

Suppose you wanted to keep a parallel data structure for your ArrayList so that all operations in the list and parallel data structure needed to be synchronized. In this case, it would be better to use external locking, since locking in a list or structure can confuse future developments in this class.

Will I provide access to my list outside my queue class?

Suppose you want to provide an access method for your list or make it visible to extensions of your Queue class. If you used an external lock object, classes that received links in the list will never be able to perform thread-safe operations on this list. In this case, it would be better to synchronize in the list and explain in the API that external accesses / modifications in the list should also be synchronized in this list.

I am sure there are more reasons why you can choose one of them, but these are two big ones that I can think of.

+5
source

Source: https://habr.com/ru/post/1484899/


All Articles