---
agentTools:
  projectIndex: https://resilience4j.readme.io/llms.txt
---

# Bulkhead

Getting started with resilience4j-bulkhead

[block:api-header]
{
  "title": "Introduction"
}
[/block]

Resilience4j provides two implementations of a bulkhead pattern that can be used to limit the number of concurrent execution:

* a `SemaphoreBulkhead` which uses Semaphores
* a `FixedThreadPoolBulkhead` which uses a bounded queue and a fixed thread pool.

The `SemaphoreBulkhead`should work well across a variety of threading and I/O models. It is based on a semaphore, and unlike Hystrix, does not provide "shadow" thread pool option. It is up to the client to ensure correct thread pool sizing that will be consistent with bulkhead configuration.

[block:api-header]
{
  "title": "Create a BulkheadRegistry"
}
[/block]

Just like the CircuitBreaker module, this module provides an in-memory `BulkheadRegistry` and a `ThreadPoolBulkheadRegistry` which you can use to manage (create and retrieve) Bulkhead instances.

[block:code]
{
  "codes": [
    {
      "code": "BulkheadRegistry bulkheadRegistry = BulkheadRegistry.ofDefaults();\n\nThreadPoolBulkheadRegistry threadPoolBulkheadRegistry = \n  ThreadPoolBulkheadRegistry.ofDefaults();",
      "language": "java"
    }
  ]
}
[/block]

[block:api-header]
{
  "title": "Create and configure a Bulkhead"
}
[/block]

You can provide a custom global BulkheadConfig. In order to create a custom global BulkheadConfig, you can use the BulkheadConfig builder. You can use the builder to configure the following properties.

[block:parameters]
{
  "data": {
    "h-0": "Config property",
    "h-1": "Default value",
    "h-2": "Description",
    "0-0": "maxConcurrentCalls",
    "1-0": "maxWaitDuration",
    "0-1": "25",
    "1-1": "0",
    "0-2": "Max amount of parallel executions allowed by the bulkhead",
    "1-2": "Max amount of time a thread should be blocked for when attempting to enter a saturated bulkhead."
  },
  "cols": 3,
  "rows": 2
}
[/block]

[block:code]
{
  "codes": [
    {
      "code": "// Create a custom configuration for a Bulkhead\nBulkheadConfig config = BulkheadConfig.custom()\n  \t.maxConcurrentCalls(150)\n  \t.maxWaitDuration(Duration.ofMillis(500))\n  \t.build();\n\n// Create a BulkheadRegistry with a custom global configuration\nBulkheadRegistry registry = BulkheadRegistry.of(config);\n\n// Get or create a Bulkhead from the registry - \n// bulkhead will be backed by the default config\nBulkhead bulkheadWithDefaultConfig = registry.bulkhead(\"name1\");\n\n// Get or create a Bulkhead from the registry, \n// use a custom configuration when creating the bulkhead\nBulkhead bulkheadWithCustomConfig = registry.bulkhead(\"name2\", custom);",
      "language": "java"
    }
  ]
}
[/block]

[block:api-header]
{
  "title": "Create and configure a ThreadPoolBulkhead"
}
[/block]

You can provide a custom global ThreadPoolBulkheadConfig. In order to create a custom global ThreadPoolBulkheadConfig, you can use the ThreadPoolBulkheadConfig builder. You can use the builder to configure the following properties.

[block:parameters]
{
  "data": {
    "h-0": "Config property",
    "h-1": "Default value",
    "h-2": "Description",
    "0-0": "maxThreadPoolSize",
    "0-1": "Runtime.getRuntime()\n.availableProcessors()",
    "1-0": "coreThreadPoolSize",
    "1-1": "Runtime.getRuntime()\n.availableProcessors() - 1",
    "2-0": "queueCapacity",
    "2-1": "100",
    "3-0": "keepAliveDuration",
    "3-1": "20 [ms]",
    "1-2": "Configures the core thread pool size",
    "0-2": "Configures the max thread pool size.",
    "2-2": "Configures the capacity of the queue.",
    "3-2": "When the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.",
    "4-0": "writableStackTraceEnabled",
    "4-1": "true",
    "4-2": "Output the stack trace error when a bulkhead exception is thrown.\nIf false, output a single line with bulkhead exception."
  },
  "cols": 3,
  "rows": 5
}
[/block]

[block:code]
{
  "codes": [
    {
      "code": "ThreadPoolBulkheadConfig config = ThreadPoolBulkheadConfig.custom()\n  .maxThreadPoolSize(10)\n  .coreThreadPoolSize(2)\n  .queueCapacity(20)\n  .build();\n        \n// Create a BulkheadRegistry with a custom global configuration\nThreadPoolBulkheadRegistry registry = ThreadPoolBulkheadRegistry.of(config);\n\n// Get or create a ThreadPoolBulkhead from the registry - \n// bulkhead will be backed by the default config\nThreadPoolBulkhead bulkheadWithDefaultConfig = registry.bulkhead(\"name1\");\n\n// Get or create a Bulkhead from the registry, \n// use a custom configuration when creating the bulkhead\nThreadPoolBulkheadConfig custom = ThreadPoolBulkheadConfig.custom()\n  .maxThreadPoolSize(5)\n  .build();\n\nThreadPoolBulkhead bulkheadWithCustomConfig = registry.bulkhead(\"name2\", custom);",
      "language": "java"
    }
  ]
}
[/block]

[block:api-header]
{
  "title": "Decorate and execute a functional interface"
}
[/block]

As you can guess Bulkhead has all sort of higher order decorator functions just like CircuitBreaker. You can decorate any `Callable`, `Supplier`, `Runnable`, `Consumer`, `CheckedRunnable`, `CheckedSupplier`, `CheckedConsumer` or `CompletionStage` with a Bulkhead.

[block:code]
{
  "codes": [
    {
      "code": "// Given\nBulkhead bulkhead = Bulkhead.of(\"name\", config);\n\n// When I decorate my function\nCheckedFunction0<String> decoratedSupplier = Bulkhead\n  .decorateCheckedSupplier(bulkhead, () -> \"This can be any method which returns: 'Hello\");\n\n// and chain an other function with map\nTry<String> result = Try.of(decoratedSupplier)\n  .map(value -> value + \" world'\");\n\n// Then the Try Monad returns a Success<String>, if all functions ran successfully.\nassertThat(result.isSuccess()).isTrue();\nassertThat(result.get()).isEqualTo(\"This can be any method which returns: 'Hello world'\");\nassertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);",
      "language": "java"
    }
  ]
}
[/block]

[block:code]
{
  "codes": [
    {
      "code": "ThreadPoolBulkheadConfig config = ThreadPoolBulkheadConfig.custom()\n    .maxThreadPoolSize(10)\n    .coreThreadPoolSize(2)\n    .queueCapacity(20)\n    .build();\n\nThreadPoolBulkhead bulkhead = ThreadPoolBulkhead.of(\"name\", config);\n\nCompletionStage<String> supplier = ThreadPoolBulkhead\n    .executeSupplier(bulkhead, backendService::doSomething);",
      "language": "java"
    }
  ]
}
[/block]

[block:api-header]
{
  "title": "Consume emitted RegistryEvents"
}
[/block]

You can register event consumer on a BulkheadRegistry and take actions whenever a Bulkhead is created, replaced or deleted.

[block:code]
{
  "codes": [
    {
      "code": "BulkheadRegistry registry = BulkheadRegistry.ofDefaults();\nregistry.getEventPublisher()\n  .onEntryAdded(entryAddedEvent -> {\n    Bulkhead addedBulkhead = entryAddedEvent.getAddedEntry();\n    LOG.info(\"Bulkhead {} added\", addedBulkhead.getName());\n  })\n  .onEntryRemoved(entryRemovedEvent -> {\n    Bulkhead removedBulkhead = entryRemovedEvent.getRemovedEntry();\n    LOG.info(\"Bulkhead {} removed\", removedBulkhead.getName());\n  });",
      "language": "java"
    }
  ]
}
[/block]

[block:api-header]
{
  "title": "Consume emitted BulkheadEvents"
}
[/block]

The BulkHead emits a stream of BulkHeadEvents. There are two types of events emitted: permitted execution, rejected execution & finished execution. If you want to consume these events, you have to register an event consumer.

[block:code]
{
  "codes": [
    {
      "code": "bulkhead.getEventPublisher()\n    .onCallPermitted(event -> logger.info(...))\n    .onCallRejected(event -> logger.info(...))\n    .onCallFinished(event -> logger.info(...));",
      "language": "java"
    }
  ]
}
[/block]