We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi all, i've a question about how to manage the access to variables shared between threads. Is this method correct or still there is the risk that a thread try to set the variable at the same time another is trying to get it? Thank you
public class myClass implements Runnable {
boolean myBoolean;
@ Override
public void run() {
}
public synchronized void setMyBoolean(boolean input) {
myBoolean = input;
}
public synchronized boolean getMyBoolean() {
return myBoolean;
}
}
Answers
If it's just a simple direct assignment, w/o expressions,
volatile
is pretty safe enough: O:-)http://docs.Oracle.com/javase/tutorial/essential/concurrency/atomic.html
http://docs.Oracle.com/javase/tutorial/essential/concurrency/atomicvars.html
Yes actually i used a pattern described in the second link, even if then the the atomic variables were described. I'm more confuse now, ahah. So, sorry if are a lot of question:
What i did is wrong, or just more than needed in this case?
What i did, just take care than two threads can't exectute at the same time the same method, or also take care to avoid interferences on the variable the method is changing? (since in the end more than one method refer to the same variable)
If i use volatile i can directly access the variable without having methods at all, what you mean for expressions?
Atomic variable are just for certain predefined kinds, right? I can't decide an object i want to pass or redefine is athomic, so how to protect it?
Sorry about the questions but is a bit a complex argument for me and i think there is a lot of mess online.
Thanks!
More than needed in this case. I-)
No need for methods if that's your taste, like mine. :P
However,
volatile
is the most fragile (although faster) of all concurrency management. :-S3 + 8
,a * .5
,sin(x) + cos(y)
, etc;In those cases, you're gonna need full
synchronized
if you intend to store the result in a concurrency field! :-<The atomic package is an advanced middle-ground between fastest
volatile
& slowestsynchronized
.It allows us to do some simple arithmetic operations, comparison checks, and assignments in an atomic way w/o
synchronized
. \m/In this ancient example, I've used compareAndSet() in order to guarantee that 1 Thread only could continue executing the rest of the method: :)>-