view src/main/java/suikwasha/distributedalgorithm/algorithms/naive/NaiveStartAlgorithm.java @ 0:38a110b13db1

added SimpleDistributedAlgorithmFramework. added NaiveAlgorithm added ChangRobertsAlgorithm added PertersonAlgorithm
author suikwasha
date Fri, 19 Oct 2012 00:05:41 +0900
parents
children
line wrap: on
line source

package suikwasha.distributedalgorithm.algorithms.naive;


import java.nio.ByteBuffer;
import java.util.Iterator;

import suikwasha.distributedalgorithm.framework.Algorithm;
import suikwasha.distributedalgorithm.framework.Context;
import suikwasha.distributedalgorithm.framework.Message;
import suikwasha.distributedalgorithm.framework.Port;

/*
 * this start algorithm for NAIVE using UnidirectedRing
 * Port1 : receiving only
 * Port2 : sending only
 */
public class NaiveStartAlgorithm implements Algorithm
{
	private long max;
	private final long num;
	
	public NaiveStartAlgorithm(long _num)
	{
		max = -1;
		num = _num;
	}
	
	public long getValue()
	{
		return max;
	}
	
	public static ByteBuffer toByteBuffer(long _value)
	{
		ByteBuffer b = ByteBuffer.allocate(8); // size of long in java
		b.putLong(_value);
		b.rewind(); // do not forget rewind() after reading/writing
		return b.asReadOnlyBuffer(); // message is read-only
	}
	
	public void execute(Context _c)
	{
		Iterator<Port> ports = _c.getPorts().iterator();
		Port receiving = ports.next();
		Port sending = ports.next();
		
		max = num;
		Message firstMessage = new Message(toByteBuffer(num));
		sending.send(firstMessage);
		
		while(true){
			Message receivedMessage;
			try{
				receivedMessage = receiving.blockingReceive();
			}catch(InterruptedException _e){
				_e.printStackTrace();
				Thread.currentThread().interrupt();
				return;
			}
			
			long value = receivedMessage.getMessage().getLong();
			if(max == value){
				Message newMessage = receivedMessage.newMessage(toByteBuffer(max));
				sending.send(newMessage);
				return;
			}
			
			max = Math.max(max,value);
			Message newMessage = receivedMessage.newMessage(toByteBuffer(value));
			sending.send(newMessage);
		}
	}
}