In the following example two threads share int counter.
The increment_thread thread increases counter by one .
The decrement_thread thread decreases counter by one .
I use semaphore to control access to counter instead of making the two methods synchronized.
Is this the proper way of using semaphore?
When should we use synchronized methods and when a semaphore?(we don't want more than one thread to access counter at the same time).
If both are proper , which is preferable?

import java.util.concurrent.Semaphore;

public class SemaphoreMultithreadingExample {
     static int counter = 0;
    static Semaphore semaphore = new Semaphore(1);

    public static void incrementCounter(){
        try {
            semaphore.acquire();
            counter++;
            semaphore.release();
        } catch (InterruptedException ex) {

        }         
    }    

    public static void decrementCounter(){
        try {
            semaphore.acquire();
            counter--;
            semaphore.release();
        } catch (InterruptedException ex) {

        }         
    }

    public static void main(String[] args) throws InterruptedException {

        Thread increment_thread = new Thread() {

            @Override
            public void run() {
                for (int i = 0; i < 5000; i++) {
                     incrementCounter();
                }

            }
        };

        Thread decrement_thread = new Thread() {

            @Override
            public void run() {
                for (int i = 0; i < 5000; i++) {
                    decrementCounter();
                }
            }
        };

        increment_thread.start();
        decrement_thread.start();

        increment_thread.join();
        decrement_thread.join();

        System.out.println("Counter : " + counter);
        System.out.println("If the result is 0 then it works ");


    }
}

Recommended Answers

All 2 Replies

The main advantage of Semaphore is that you can limit access to n threads, not just one thread, at a time. Personally I would use synchronised to limit to one thread at atime, mainly because its simpler and more obvious code.

I think that a disadvantage of semaphore is that the thread using semaphore.acquire() could be interrupted.
I 've read that when we are dealing with a small number of threads synchronized methods are faster but as the number of threads increases semaphores are faster.
Thank you for your answer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.