Skip to content

Instantly share code, notes, and snippets.

@icarofreire
Created March 13, 2024 17:25
Show Gist options
  • Save icarofreire/179205fc4c4c70b9ec60bf9c562fca9b to your computer and use it in GitHub Desktop.
Save icarofreire/179205fc4c4c70b9ec60bf9c562fca9b to your computer and use it in GitHub Desktop.
package vigilancia.service;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
/*
* Classe para operações de concorrência;
* Evitar que o usuário realize muitiplas requisições subsequentemente;
*
* https://www.baeldung.com/spring-webclient-limit-requests-per-second
*/
public class Concurrency {
private static final long limitSeconds = 2;
private static final long millis = 2000;//2;
private static final int MAX_CONCURRENT = 5;
private static final int MAX_CONCURRENT_SEQ = 5;
private static final AtomicInteger CONCURRENT_REQUESTS = new AtomicInteger();
private static final AtomicInteger CONCURRENT_REQUESTS_SEQ = new AtomicInteger();
private static LocalDateTime tempoAnt = LocalDateTime.now();
public static int protect() {
try {
if (CONCURRENT_REQUESTS.incrementAndGet() > MAX_CONCURRENT) {
throw new UnsupportedOperationException("max concurrent requests reached");
}
LocalDateTime atual = LocalDateTime.now();
long seconds = ChronoUnit.SECONDS.between(tempoAnt, atual);
if(CONCURRENT_REQUESTS.get() > 0 && seconds <= limitSeconds){
CONCURRENT_REQUESTS_SEQ.incrementAndGet();
/**\/ [fase de BLOCK]; */
// System.out.println(">>>>>>>>> [BLOCK] >>>>>>>>>");
// System.out.println( seconds );
// System.out.println( CONCURRENT_REQUESTS.get() );
// System.out.println( CONCURRENT_REQUESTS_SEQ.get() );
if(CONCURRENT_REQUESTS_SEQ.get() >= MAX_CONCURRENT_SEQ){
/**\/ [BLOCK usuário]; */
// System.out.println(">>>>>>>>> [BLOCK XX] >>>>>>>>>");
}
}
tempoAnt = atual;
TimeUnit.SECONDS.sleep(millis);
return 1;
}catch(InterruptedException e){;
return 0;
} finally {
CONCURRENT_REQUESTS.decrementAndGet();
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
System.out.println(">>>>>>>>> MAX >>>>>>>>");
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment