954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

load balancing

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();
	}
}
solomon_13000
Junior Poster in Training
88 posts since Jul 2009
Reputation Points: 24
Solved Threads: 0
 

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

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

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.

nmaillet
Posting Whiz in Training
236 posts since Aug 2008
Reputation Points: 69
Solved Threads: 53
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: