RMI + Multithreading

2 respostas
I

E ai galera, blz !?
To começando agora no fórum e já venho com uma dúvida:
Alguém sabe se é possível utilizar multithreading com RMI ?
Vou ser mais especifico:
Eu tenho as interfaces PI e Server e as
classes Servidor (que contém o "main"), PI_Impl e ServerImpl que ficam no servidor
além d classe Client que fica no cliente.
Gostaria de saber se é possivel eu tendo um número variável de clientes (definido como parametro de linha de comando)
ter todas as minhas requisições atendidas pelo servidor.
As minhas classes:

Classe Servidor
import java.rmi.*;

public class Servidor{
	public static void main( String args[]){

		// Cria e instala o gerente de segurança
	        System.setSecurityManager( new RMISecurityManager());
		try {

			// cria a instância do objeto para registro
			System.out.println("SERVIDOR: criando um Server");
			ServerImpl srv = new ServerImpl();

			// Liga a instância do objeto ao registro
			System.out.println("Servidor RMI: ligando a variável \"srv\" ao nome - Server");
			
			for(int i = 0;  i < 15; i ++){
				Naming.rebind("Server", srv);
				System.out.println("Servidor gerenteBanco pronto.");
			}
		}
		catch (Exception e) {
			System.out.println("Servidor RMI: ocorreu uma exceção - :"+
				e.getMessage());
				e.printStackTrace();
		}
	}

}
Interface Server
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.Remote;

public interface Server extends Remote{

	public PI getPI() throws RemoteException;
}
Classe ServerImpl
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class ServerImpl extends UnicastRemoteObject implements Server{

	private PI pi;
	
	protected ServerImpl() throws RemoteException {
		super();
	}	

	public synchronized PI getPI() throws RemoteException{
	      return new PI_Impl(2);
    }
}
Classe Client
import java.rmi.Naming;

public class Client implements Runnable{
	private String host;
	private String id;
	
	public Client(String id, String host){
		this.id = id;
		this.host = host;		
	}
	
	public void run(){
		
		try {
			// Obtem uma instância para o objeto remoto
			System.out.println(id + ": pesquisando nome - Server");
			String url = new String("rmi://"+host+"/Server");
			
			System.out.println(id + ": conseguindo referência remota");
			Server srv = (Server) Naming.lookup(url);

			System.out.println(id + ": conseguindo objeto PI");
			PI pi = srv.getPI();

			float resposta = pi.calcula();

			System.out.println(id + ": pi = " + resposta);

		}
		catch (Exception e) {
			System.out.println(id + ": ocorreu uma exceção - :"+
				e.getMessage());
				e.printStackTrace();
		}
	}

	public static void main(String args[]){

		// Verifica a contagem de argumentos
		if( args.length < 2 ){
			System.err.println("Uso:");
			System.err.println("java Cliente <servidor> <nro de clientes>");
			System.exit(1);
		}
		
		int nroClientes = Integer.parseInt(args[1]);
		for (int i = 0; i < nroClientes; i++){
			Client c = new Client("Cliente " + i, args[0]);
			Thread t = new Thread(c);
			t.start();
		}					
		
		System.exit(1);
	}

}
Interface PI
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface PI extends Remote{
	
	public float calcula() throws RemoteException;

}
Classe PI_Impl
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;


public class PI_Impl extends UnicastRemoteObject implements PI{


    private float area;        
    private float x;           
    private int precisao;	   
    private float incremento;  


    public PI_Impl(int precisao) throws RemoteException{
        this.area = 0;
        this.precisao = precisao;
        this.x = 0;
    }


    public float f(float x) {

        return (float) (4.0 / (1.0 + (x * x)));

    }

    public float calcula() throws RemoteException{

        float n = 1;
        for (int i = 0; i < precisao; i++) {
            n *= 10.0;
        }

        incremento = (float) (1.0 / n);

        for (int i = 0; i < n; i++) {
            area += f(x);
            x += incremento;
        }

        return area / (float) n;
    }
}

Desde já agradeço.

Inspector.

2 Respostas

B

Ola,

Não deu pra vre seu codigo a fundo, mas sim, é possível sim, e diria pra vc que RMI funciona perfeitamente com multithread,
trabalho com RMI a uns 3 a 4 anos, e garanto pra vc que isto é possível.

I

Blz,
Pelo menos eu sei q não to perdendo tempo
procurando. rsrsrsrs.

Valeu.

Criado 18 de junho de 2008
Ultima resposta 19 de jun. de 2008
Respostas 2
Participantes 2