Search code examples
androidtcpqueuevolatile

Is the volatile mark necessary for a queue with one thread adding and another reading?


in response to some comments in this thread, I am wondering if making a queue that will have one thread adding to it and another thread reading from it requires the 'volatile' mark?

I suppose most cases would be alright, but in the case of reading and writing in a queue of size 1 could cause issues without it?

Goal:

  • a thread safe queue where I can post messages to be sent over a TCP socket connection. The out stream will be managed by another class who will check if the queue is empty at the beginning of each loop

My Ideas/Thoughts:

  • Maybe there is a built-in Queue for TCP sockets that I have not found in my research?
  • Is volatile good to use in this circumstance, or should I use a blocking or locking call?

Thanks in advance.


Solution

  • Use lock objects if you want synchronized access like you've mentioned.

    Volatile is not really used in this context. Declaring your List myList object as volatile would mean that if you ever tried to instantiate a new Object and set it to the myList variable, then the thread would be guaranteed to know that there is a new object assigned to it (roughly). It doesn't block or synchronize anything to do with the actual object.

    Basically, like you said, you need to be sure that when you are reading or writing to the list, that nothing will mess the list up and cause an unexpected error. For stopping two things from happening at the same time, use lock objects and the Java synchronized keyword, or use a List type that already synchronizes read/writes for you.