{"record":{"id":"dde81c9e24b42503","repo":"Netflix/Hystrix","slug":"hystrixrequestcontext-initializecontext-must-be","errorCode":null,"errorMessage":"HystrixRequestContext.initializeContext() must be called at the beginning of each request before RequestVariable functionality can be used.","messagePattern":"HystrixRequestContext\\.initializeContext\\(\\) must be called at the beginning of each request before RequestVariable functionality can be used\\.","errorType":"exception","errorClass":"IllegalStateException","httpStatus":null,"severity":"error","filePath":"hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixRequestVariableDefault.java","lineNumber":76,"sourceCode":"    static final Logger logger = LoggerFactory.getLogger(HystrixRequestVariableDefault.class);\n\n    /**\n     * Creates a new HystrixRequestVariable that will exist across all threads\n     * within a {@link HystrixRequestContext}\n     */\n    public HystrixRequestVariableDefault() {\n    }\n\n    /**\n     * Get the current value for this variable for the current request context.\n     * \n     * @return the value of the variable for the current request,\n     *         or null if no value has been set and there is no initial value\n     */\n    @SuppressWarnings(\"unchecked\")\n    public T get() {\n        if (HystrixRequestContext.getContextForCurrentThread() == null) {\n            throw new IllegalStateException(HystrixRequestContext.class.getSimpleName() + \".initializeContext() must be called at the beginning of each request before RequestVariable functionality can be used.\");\n        }\n        ConcurrentHashMap<HystrixRequestVariableDefault<?>, LazyInitializer<?>> variableMap = HystrixRequestContext.getContextForCurrentThread().state;\n\n        // short-circuit the synchronized path below if we already have the value in the ConcurrentHashMap\n        LazyInitializer<?> v = variableMap.get(this);\n        if (v != null) {\n            return (T) v.get();\n        }\n\n        /*\n         * Optimistically create a LazyInitializer to put into the ConcurrentHashMap.\n         * \n         * The LazyInitializer will not invoke initialValue() unless the get() method is invoked\n         * so we can optimistically instantiate LazyInitializer and then discard for garbage collection\n         * if the putIfAbsent fails.\n         * \n         * Whichever instance of LazyInitializer succeeds will then have get() invoked which will call\n         * the initialValue() method once-and-only-once.","sourceCodeStart":58,"sourceCodeEnd":94,"githubUrl":"https://github.com/Netflix/Hystrix/blob/5ce3bc58c38e7ca60ef2fe0e516e390e294ad941/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixRequestVariableDefault.java#L58-L94","documentation":"Hystrix request-scoped state (request cache, request log, HystrixRequestVariable) lives in a HystrixRequestContext attached to the current thread. Reading any HystrixRequestVariable throws this IllegalStateException when HystrixRequestContext.getContextForCurrentThread() returns null, i.e. no context was initialized on this thread before the variable was used.","triggerScenarios":"Calling get() on a HystrixRequestVariableDefault (directly or via request cache/request log features: getCacheKey(), HystrixRequestLog.getCurrentInstance()) on a thread that never called HystrixRequestContext.initializeContext(); using commands with request caching enabled inside thread pools or async executors that were not context-wrapped.","commonSituations":"Servlet filter that calls initializeContext()/shutdown() missing or mapped to the wrong URL pattern; invoking Hystrix commands from @Async methods, CompletableFuture, or custom executors where the context ThreadLocal was never set; integration tests that forget to initialize the context.","solutions":["Initialize the context at the start of each request and shut it down at the end: HystrixRequestContext.initializeContext() ... context.shutdown() in a finally block, typically in a servlet Filter.","For background threads, wrap the work with HystrixContextRunnable/HystrixContextCallable so the context is propagated.","In tests, wrap test bodies with initializeContext/shutdown in setUp/tearDown.","If you do not need request caching or logging, disable them (hystrix.command.<key>.requestCache.enabled=false, requestLog.enabled=false) to avoid touching the request context."],"exampleFix":"// before\nString v = new MyCommand(cmdKey).execute(); // getCacheKey set, no context initialized -> IllegalStateException\n\n// after\nHystrixRequestContext ctx = HystrixRequestContext.initializeContext();\ntry {\n    String v = new MyCommand(cmdKey).execute();\n} finally {\n    ctx.shutdown();\n}","handlingStrategy":"validation","validationCode":"if (HystrixRequestContext.getContextForCurrentThread() == null) {\n    HystrixRequestContext.initializeContext(); // or reject/warn before using request-scoped features\n}","typeGuard":null,"tryCatchPattern":"HystrixRequestContext context = HystrixRequestContext.getContextForCurrentThread();\nif (context == null) {\n    context = HystrixRequestContext.initializeContext();\n    try {\n        // request-scoped work\n    } finally {\n        context.shutdown();\n    }\n}","preventionTips":["Install a servlet filter (or framework interceptor) that initializes and shuts down HystrixRequestContext per request.","Wrap background work in HystrixContextRunnable/HystrixContextCallable to propagate the context.","Initialize/shutdown the context in test setUp/tearDown when request caching or logging is exercised."],"tags":["hystrix","request-context","threadlocal","servlet-filter"],"backgroundTag":null,"analyzedSha":"5ce3bc58c38e7ca60ef2fe0e516e390e294ad941","analyzedAt":"2026-08-14T10:55:35.600Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}