Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java volatile objects in non volatile objects

// structure is like this, but not exact formation.
class queue
{
    volatile List<pieceOfWork> worksWaiting;
}

List<queue> qs; //  pieceOfWork has only some primitive arrays and strings.

Is it safe to read/write(not destroy, not create) elements of "Qs" from N threads at the same time?

"WorksWaiting" is meant to synchronize between controller thread(1 or 2) and a controlled thread (N) while N controlleds reading/writing to Queues concurrently.

Deletion/creation of queue will be made of controller threads.

Thanks you.

 th read   th write 
(cpu sse) (gpu opencl executor)
 ^         ^
 |         |
 W W W W W W  ....w<--- controller thread adding new works to queue and
                                                  deleting finished ones.
                                               also splits a work item if 
                                             it is not finished in short time.
like image 897
huseyin tugrul buyukisik Avatar asked Jun 29 '26 19:06

huseyin tugrul buyukisik


2 Answers

As long as the referece to queue doesn't change (ie you don't create and use a new queue during execution), it doesn't have to be volatile (it makes no difference). Likewise, if the reference to the list inside queue doesn't change (ie you don't create and use a new list during execution) the list doesn't have to be volatile (it also makes no difference)

What does matter is that the list is a threadsafe implementation - whose internal variables are volatile and whose code is synchronised as required etc, because it's the references the list is holding (to the work objects) and its internals that will be mutated and these changes need to be visible to all threads (volatile).

Your code is irrelevant - it's the list that needs to be threadsafe.

like image 151
Bohemian Avatar answered Jul 02 '26 09:07

Bohemian


Objects are not volatile. Variables are volatile. It is safe to play with the variable worksWaiting. It is not safe to play with the object it refers to unless it is documented as thread-safe or you synchronize all access to it correctly.

like image 40
user207421 Avatar answered Jul 02 '26 09:07

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!