I simulated a load balancing concept using java code. It works well when two services access the display method concurrently. However if there are more than two request then this algorithm is likely to fail. Therefore how could I solve this problem? Your help is kindly appreciated. Thank You.

import java.util.ArrayList;

public class scheduler extends Thread{

	int i = 0;
	ArrayList a = null;
	
	public void setSession()
	{
		a = new ArrayList();
		a.add(new String("running"));
	}
	
	public void destroySession(){
		a=null;
	}
	
	public int getSessionSize(){
		return (a!=null)? a.size():0;
	}
	
	public void display(){
		int size = getSessionSize();
		if(size==0){
			setSession();
			System.out.println("1");
		}else{
			destroySession();
			System.out.println("2");
		}
	}
	
	public void run(){
		while(true){
		    try {
		    	display();
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
		}
	}
	
	public static void main(String[] args){
		scheduler s1 = new scheduler();
		s1.start();
	}
}

Could you explain your algorithm?
And the reason that it fails.

I am assuming you are referring to multiple threads accessing the display() method, from the same object instance. If so, your code would cause some inconsistent errors (may work perfectly, or may fail). This is because instructions between multiple threads do not, by default, completely execute an entire method before allowing another to execute. What may happen: size gets set in thread 1, then size gets set in thread 2, then the following instructions are executed.

Try adding synchronized to the display() method:

public synchronized void display(){
	int size = getSessionSize();
	if(size==0){
		setSession();
		System.out.println("1");
	}else{
		destroySession();
		System.out.println("2");
	}
}

This will ensure the method completes execution by one thread, before another can execute it. What concerns me, is that the other public methods are susceptible to the same issues. Not necessarily within the method, but by the executing objects. You should read up on threading and concurrency.

Good luck.

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.