Daniel :
There is a thread that keeps tracking new emails while a static variable tracking
is true. It looks like this:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
tracking = true;
while(tracking){
//check emails
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
I implemented a function to stop tracking emails, that basically sets tracking
to false.
Tracking is just a private static boolean
which I use only inside the class that does these tasks.
Can this approach lead me to any problem?
Ivan :
If there are several threads that read and write to the same variable you need to use synchronization (e.g. an AtomicBoolean
). In this particular case it is enough to declare tracking
as volatile
so that new value set to that variable in one thread will be correctly visible in another thread:
private static volatile boolean tracking;