Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Thread Ordering Without Using Synchronized [Snippet]

DZone's Guide to

Thread Ordering Without Using Synchronized [Snippet]

Want to order your threads without resorting to synchronized? Here's how you can get with you want with some help from our old friend volatile.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

Say we have a requirement that thread 0 will print 0, thread 1 will print 1, thread 2 will print 2, etc. The following should be the output.

thread 0 prints 0
thread 1 prints 1
thread 2 prints 2
thread 3 prints 3
thread 0 prints 0
thread 1 prints 1
thread 2 prints 2
thread 3 prints 3
thread 0 prints 0
thread 1 prints 1
thread 2 prints 2
thread 3 prints 3


To illustrate the point, I've provided a small, fully running program here. It's self-explanatory.

But how can we do that while avoiding implementing "synchronized".

Answer: Use "volatile" as seen in this code snippet.

//package threadOrderingVolatile;

public class Solution {
    static volatile int counter = 0;
    static int print = 0;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Thread[] ths = new Thread[4];
        for (int i = 0; i < ths.length; i++) {
            ths[i] = new Thread(new MyRunnable(i, ths.length));
            ths[i].start();
        }
    }

    static class MyRunnable implements Runnable {
        final int thID;
        final int total;

        public MyRunnable(int id, int total) {
            thID = id;
            this.total = total;
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub

            while (true) {
                if (thID == counter) {
                    System.out.println("thread " + thID + " prints " + print);
                    print++;
                    if (print == total)
                        print = 0;
                    counter++;
                    if (counter == total)
                        counter = 0;
                } else {
                    try {
                        Thread.sleep(30);
                    } catch (InterruptedException e) {
                        // log it
                    }
                }
            }
        }

    }

}


I hope this helps.

And here is a GitHub link that leads to a readme with an explanation and a bit modified code.

Cheers!

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
synchronized ,volatile ,java ,thread ordering

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}