Showing posts with label java semaphore example. Show all posts
Showing posts with label java semaphore example. Show all posts

Thursday, October 7, 2010

Example for java.util.concurrent.Semaphore usage

Let's try to increment a simple integer variable without any synchronization.
See what happens if we don't care about critical sections :)


Yes even we are not able to increment an integer without using any synchronization primitives.So we see the values of "i" 10-11-10 which are highlighted in the messages pane of my ide.

And...Here is the succesfull result in which we are using a Semaphore from java 1.5 (Tiger).

import java.util.concurrent.locks.*;
import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    int i = 0;

    public static void main (String[] args) {
        final SemaphoreExample example = new SemaphoreExample();
        final Semaphore semaphore = new Semaphore (1);

        final Runnable r = new Runnable () {
            public void run () {
                while (true) {
                    try {
                        semaphore.acquire();
                        example.printSomething ();
                        Thread.sleep (1000);
                        semaphore.release();
                    } catch (Exception ex) {
                        System.out.println (" -- Interrupted...");
                        ex.printStackTrace ();
                    }
                }
            }
        };

        new Thread (r).start ();
        new Thread (r).start ();
        new Thread (r).start ();
    }

    public void printSomething (){
        i++;
        System.out.println (" -- current value of the i :"+ i);
    }
}