Developing a synchonisation algorithim with Semaphores

Viewed 44

Hi i want to design an algorithim in Java that prevents deadlock for simple train simulator, im trying to solve the problem of two trains that want to move into the critical section Once a thread is in the critcal section it basically sleeps for a random period of time whilst the other waits Im not worried about starvation

So far i have this and its a rough implementation of dekkers algorithim.

public void runTrain() throws RailwaySystemError {
        Clock clock = getRailwaySystem().getClock();
        Railway nextRailway = getRailwaySystem().getNextRailway(this);


        while (!clock.timeOut() && !errorOccurred()) {
            announceIntention();
            getFlag.putSFlag(this); 
            while(nextRailway.getFlag.hasFlag(this)) { 
                if(getSharedFlag.hasFlag(this)) { 
                    getFlag.takeFlag(this); 
                    while(getSharedFlag.hasFlag(this)) { 
                        sleep(); 
                    }
                    getFlag().putFlag(this); // else

                }

            }
            crossPass();
            if (!getFlag.hasFlag(this)){
                getSharedFlag.putFlag(this);
            }


            getFlag().takeFlag(this);
        }
    }

This code is almost the same for both trains.

Im trying to accomplish the same thing however exclusivley using Java semaphores the algorithim doesnt need to be bothered with starvation just preventing deadlock

Any help would be appreciated thanks

1 Answers

If you want to use Semaphore for mutual exclusion:

import java.util.concurrent.Semaphore;

public class Train {
    static Semaphore semaphore = new Semaphore(1);

    public void crossPath() throws InterruptedException {
        semaphore.acquire();
        try {
            //critical section
        } finally {
            semaphore.release();
        }
    }

}

Note the use of try-finally. This is so we can be sure that even of the code in the critical section throws an exception we will release the lock.

In Java you can also use the synchronized keyword to achieve mutual exclusion. Here we synchronize by using the intrinsic lock of Train class. This means that no two instances of Train can execute the code in the synchronized block concurently.

public class Train {
    public void crossPath(){
        synchronized (Train.class){
            ///critical section - only one instance of Train can be here at a given time
        }
    }
    
}
Related