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();
}
}