mardi 17 décembre 2019

one java memoryFlushing volatile: A good programdesign?

its a related question to this one: java: using volatile at one variable VS each variable

i have one or more different objects. i want to change some state in it and then i want to make that state visible to other threads.

For performance reasons i dont want to make each member variable in that objects volatile. And sometimes i want to use these objects in a single thread application. So in that case the volatile would be also bad.

So i had the following:

//these following mehtods change some internal variable state. These variables are not volatile or synchronized

boolean volatile memoryFlusher=false;

Thread1:

obj1->changeSomeState();
obj1->changeMoreState();
obj2->alsoSomeStateChange();

//and now i want to make that state visible to others

memoryFlusher=false; //volatile write


Thread2:

boolean tmp=memoryFlusher; // volatile read but variable is not used again

obj1->getState();
obj2->getState();

So till now its more or less the same to my related question i linked at the beginning.

So now i want to ask the following:

My memoryFlusher is not optimzed away? (unanswerd in my other question) Each volatile write/read flushes all memoryState of ALL? other (also none-volatile-)variables?

And now the really new question:

is that a good design, i do there? Cause i didnt saw any code anywhere like this, i posted here.

Should i program my Progamm in a other way? Is there a other best practise to increase the performance and getting visibilty? Is there other best practise in the program-design view, not having doing something like this?

Aucun commentaire:

Enregistrer un commentaire