Thursday, March 13, 2014

Lamport algorithm for logical clock synchronization

A very basic implementation of Lamport logical clock synchronization.



public class Lamport {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Process p1,p2,p3;
        p1= new Process(1);
        p2= new Process(2);
        p3= new Process(3);
        System.out.println("P1  P2   p3");
        System.out.println(p1.time+"  "+ p2.time+"  "+p3.time);
        p1.passMessege(p3);
        System.out.println("P1->P3");
        System.out.println(p1.time+"  "+ p2.time+"  "+p3.time);
        p2.passMessege(p3);
         System.out.println("P2->P3");
        System.out.println(p1.time+"  "+ p2.time+"  "+p3.time);
        p3.passMessege(p2);
         System.out.println("P3->P2");
        System.out.println(p1.time+"  "+ p2.time+"  "+p3.time);
        
    }
    
}


public class Process {
    
    public int time;
    public int timestep;
    
    public void passMessege(Process p)
    {
        time+=timestep;
        p.time+=p.timestep;
        if(p.time<=time)
            p.time=time+1;
    }
    public Process(int tstep)
    {
        time=0;
        timestep=tstep;
    }
}

Output
P1  P2   p3
0  0  0
P1->P3
1  0  3
P2->P3
1  2  6
P3->P2
1  10  9