I recently discovered that Java’s ThreadPoolExecutor comes with a built-in back-pressure mechanism, and it’s surprisingly useful.
Consider a scenario where you use a thread pool to process large data encryption tasks. To avoid running into an OutOfMemoryError, you’d normally need to implement a way to slow down or block the threads submitting tasks.
With ThreadPoolExecutor, this is straightforward: simply configure the RejectedExecutionHandler to use CallerRunsPolicy.
This setting forces the submitting thread to execute the task itself whenever the pool and its queue are saturated. Since the submitting thread is now busy doing work, it naturally slows down task submission — effectively applying back-pressure.
Simple and elegant, right?
Top comments (0)