Skip to content

Instantly share code, notes, and snippets.

@dp-singh
Last active August 9, 2023 14:27
Show Gist options
  • Save dp-singh/caf2957160205b0c33514098d77bc7ee to your computer and use it in GitHub Desktop.
Save dp-singh/caf2957160205b0c33514098d77bc7ee to your computer and use it in GitHub Desktop.
sample to show how to achieve rate limiter
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
public class ImageProcessor {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final AtomicBoolean isProcessing = new AtomicBoolean(false);
private final Handler mainHandler = new Handler(Looper.getMainLooper()); // For UI thread operations
/**
processCurrentBitmap(Bitmap bitmap) Method:
This method is responsible for managing the processing flow.
It first checks if a bitmap is currently being processed using the isProcessing flag.
If no bitmap is currently being processed, it sets the isProcessing flag to true and submits a task to the executor.
The executor's task attempts to process the provided bitmap using the processBitmap method.
*/
private void processCurrentBitmap(Bitmap bitmap) {
if (isProcessing.compareAndSet(false, true)) {
executor.submit(() -> {
try {
processBitmap(bitmap); // Process the provided bitmap
} finally {
isProcessing.set(false); // Reset the processing flag
}
});
}else{
// Image is already processing, ignore this job
}
}
private void processBitmap(Bitmap bitmap) {
// Your bitmap processing logic here
}
public void shutdown() {
executor.shutdown();
}
// Example usage in an Android context
public static void main(String[] args) {
ImageProcessor processor = new ImageProcessor();
// Simulate incoming bitmaps (replace with actual bitmaps)
for (int i = 0; i < 10; i++) {
Bitmap bitmap = Bitmap.createBitmap(640, 480, Bitmap.Config.ARGB_8888);
processor.processBitmap(bitmap);
}
processor.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment