1. import java.io.*;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3. public class ConfigGuard {
  4. private static final int MAX_REQUESTS = 10; // Maximum number of requests allowed per time window
  5. private static final long TIME_WINDOW_MS = 60000; // Time window in milliseconds (e.g., 60 seconds)
  6. private static final AtomicInteger requestCount = new AtomicInteger(0);
  7. private static final Object lock = new Object();
  8. public static boolean isAllowed() {
  9. synchronized (lock) {
  10. if (requestCount.get() >= MAX_REQUESTS) {
  11. return false; // Rate limit exceeded
  12. }
  13. requestCount.incrementAndGet();
  14. return true; // Request allowed
  15. }
  16. }
  17. public static void resetCount() {
  18. synchronized (lock) {
  19. requestCount.set(0);
  20. }
  21. }
  22. public static void main(String[] args) throws IOException {
  23. // Example Usage (Simulate reading a configuration file)
  24. if (isAllowed()) {
  25. System.out.println("Accessing configuration file...");
  26. // Simulate reading from a config file
  27. try (BufferedReader reader = new BufferedReader(new FileReader("config.properties"))) {
  28. String line;
  29. while ((line = reader.readLine()) != null) {
  30. System.out.println("Line: " + line);
  31. }
  32. } catch (IOException e) {
  33. System.err.println("Error reading config file: " + e.getMessage());
  34. }
  35. resetCount(); // Reset count after successful access
  36. } else {
  37. System.out.println("Rate limit exceeded. Access denied.");
  38. }
  39. }
  40. }

Add your comment