Java threads sharing static variable

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;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111472&siteId=1