Depois de descobrir como saber se uma thread conseguiu ou nao um lock (http://www.guj.com.br/posts/list/19700.java), agora estou com um problema mais interessante e desafiador. :D
Imagine um processo multi-thread que faz requisicoes a um servidor HTTP. Esse processo eh relativamente rapido e nao queremos sobrecarregar o servidor. Dessa forma pensei no seguinte: estabelecer um delay entre uma e outra requisicao. Se isso fosse serial (uma thread), resolveria, mas em paralelo precisa de uma coordenacao entre as threads.
A implementacao ficou assim (o Runner eh o mesmo do topico acima):
ProcessoDelay:import EDU.oswego.cs.dl.util.concurrent.Mutex;
public class ProcessoDelay {
private static final int DELAY_REQUEST = 1000; // em milissegundos
private static final int SLEEP_TIME = DELAY_REQUEST / 2;
private static final Mutex mutex = new Mutex();
private static long lastTime = System.currentTimeMillis() - DELAY_REQUEST;
private String nome;
public void initTask(String nome) {
this.nome = nome;
try {
acquireLockTime();
doTask();
} catch (Exception e) {
e.printStackTrace();
} finally {
releaseLockTime();
}
}
private void doTask() throws Exception {
System.out.println("thread " + nome + " - time: " + System.currentTimeMillis() + " - delay:" + (System.currentTimeMillis() - lastTime));
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void acquireLockTime() throws InterruptedException {
while (true) {
// aqui acho que poderia ser simplesmente: while (!mutex.attempt(SLEEP_TIME));
while (!mutex.attempt(0)) {
Thread.sleep(SLEEP_TIME);
}
if (System.currentTimeMillis() <= (lastTime + DELAY_REQUEST)) {
mutex.release();
} else {
break;
}
}
}
private void releaseLockTime() {
lastTime = System.currentTimeMillis();
mutex.release();
}
}
thread 2 - time: 1107526591984 - delay:1010
thread 16 - time: 1107526592996 - delay:1002
thread 19 - time: 1107526594007 - delay:1001
thread 20 - time: 1107526595038 - delay:1001
thread 3 - time: 1107526596050 - delay:1002
thread 1 - time: 1107526597061 - delay:1001
thread 4 - time: 1107526598073 - delay:1002
thread 6 - time: 1107526599084 - delay:1001
thread 12 - time: 1107526600096 - delay:1002
thread 7 - time: 1107526601107 - delay:1001
thread 18 - time: 1107526602119 - delay:1002
thread 13 - time: 1107526603130 - delay:1001
thread 5 - time: 1107526604142 - delay:1002
thread 9 - time: 1107526605153 - delay:1001
thread 14 - time: 1107526606184 - delay:1001
thread 15 - time: 1107526607196 - delay:1002
thread 8 - time: 1107526608207 - delay:1001
thread 17 - time: 1107526609219 - delay:1002
thread 11 - time: 1107526610230 - delay:1001
thread 10 - time: 1107526611242 - delay:1002
Existe uma maneira melhor/mais simples de resolver esse problema? Opinioes sao bem-vindas. :D
Marcio Kuchma