xo4-va
Last Updated: February 25, 2016
·
390
· maandree
Ab927485bccfcf35ba4583723876063f

Thread safety in Java

Before you do something like:

http://stackoverflow.com/questions/16159203/why-does-this-java-program-terminate-despite-that-appears-that-it-shouldnt-and

Learn volatile and how to use synchronized.

Without volatile, the posted code is effectively:

class A
{   static int x = 1, y = 2;
    public static void main(String[] args)
    {
        new Thread()
        {
            @Override
            public void run()
            {   for (;;)
                    if (A.x + 1 != A.y)
                    {
                        System.out.println(A.x + " " + A.y);
                        System.exit(1);
            }       }
        }.start();
        for (;; x++, y++) ;
}   }

But this is fine, as long as you use synchronized around blocks of code where
multiple threads my read or modify variables:

class A
{   static int x = 1, y = 2;
    public static void main(String[] args)
    {
        new Thread()
        {
            @Override
            public void run()
            {   for (;;)
                    synchronized(A.class) /* with same mutex as the other synchronized */
                    {   if (A.x + 1 != A.y)
                        {
                            System.out.println(A.x + " " + A.y);
                            System.exit(1);
            }       }   }
        }.start();
        for (;;)
            synchronized(A.class)
            {
                x++;
                y++;
            }
}   }
Say Thanks
Respond