Como ficaria um método de classe (static) que efetuam cálculos, formatações, etc, sem precisar acessar valores staticos da classe mas sim passados por parâmetros em um ambiente multi-thread?
Como o método é estático e só existe uma única instância dele no processo da jvm, se duas ou mais threads acessarem esse método e passar valores diferentes em seus parâmetros, qual seria o tratamento?
Cada thread teria em sua pilha de execução uma cópia desses valores e o método trataria de forma diferente ou
O valor da segunda thread acabaria afetando o valor da primeira, comprometendo a atomicidade do método?
Seria necessário criar um método thread-safe caso ele seja declarado como static para evitar as "condições de corrida"?
Alguém pode me ajudar?
Vide exemplo de código:
public class StaticValorUtil {
public static String asString(Object vlr){
return vlr.toString();
}
public static Integer asInteger(Object vlr){
return Integer.parseInt(asString(vlr));
}
}
Agora a classe que será a thread
public class Gerente implements Runnable{
private String id;
private int inicio;
public Gerente(int inicio, String id){
this.id = id;
this.inicio = inicio;
}
@Override
public void run() {
for(int i = inicio; i < inicio + 100; i++){
System.out.println("Executando linha " + ValorUtil.getInstance(i).asInteger()
+ " da thread " + ValorUtil.getInstance(id).asString());
}
}
}
Agora o cliente que iniciará a thread
public static void main(String[] args) {
Gerente g1 = new Gerente(0,"Gerente 1");
Gerente g2 = new Gerente(200, "Gerente 2");
Gerente g3 = new Gerente(300,"Gerente 3");
Gerente g4 = new Gerente(400,"Gerente 4");
Gerente g5 = new Gerente(500,"Gerente 5");
Thread t1 = new Thread(g1);
Thread t2 = new Thread(g2);
Thread t3 = new Thread(g3);
Thread t4 = new Thread(g4);
Thread t5 = new Thread(g5);
Gerente g6 = new Gerente(600, "Gerente 6");
Gerente g7 = new Gerente(700, "Gerente 7");
Gerente g8 = new Gerente(800, "Gerente 8");
Gerente g9 = new Gerente(900, "Gerente 9");
Gerente g10 = new Gerente(1000, "Gerente 10");
Thread t6 = new Thread(g6);
Thread t7 = new Thread(g7);
Thread t8 = new Thread(g8);
Thread t9 = new Thread(g9);
Thread t10 = new Thread(g10);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
t10.start();
}
}
É possível garantir, sem o uso de synchronized, que, apesar do método ser estático, que os valores dos parâmetros passados por uma thread para o método "asInteger()" da classe "StaticValorUtil" não sejam afetados por outra thread??