{"id":"2694ce9bc7373c3c","repo":"apache/kafka","slug":"topic-pattern-to-subscribe-to-cannot-be-null","errorCode":null,"errorMessage":"Topic pattern to subscribe to cannot be null","messagePattern":"Topic pattern to subscribe to cannot be null","errorType":"validation","errorClass":"java.lang.IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java","lineNumber":2249,"sourceCode":"                \" otherThread(id: \" + currentThread.get() + \")\"\n            );\n        refCount.incrementAndGet();\n    }\n\n    /**\n     * Release the light lock protecting the consumer from multithreaded access.\n     */\n    private void release() {\n        if (refCount.decrementAndGet() == 0)\n            currentThread.set(NO_CURRENT_THREAD);\n    }\n\n    private void subscribeInternal(Pattern pattern, Optional<ConsumerRebalanceListener> listener) {\n        acquireAndEnsureOpen();\n        try {\n            throwIfGroupIdNotDefined();\n            if (pattern == null || pattern.toString().isEmpty())\n                throw new IllegalArgumentException(\"Topic pattern to subscribe to cannot be \" + (pattern == null ?\n                    \"null\" : \"empty\"));\n            log.info(\"Subscribed to pattern: '{}'\", pattern);\n            applicationEventHandler.addAndGet(new TopicPatternSubscriptionChangeEvent(\n                pattern,\n                listener,\n                defaultApiTimeoutDeadlineMs()\n            ));\n        } finally {\n            release();\n        }\n    }\n\n    /**\n     * Subscribe to the RE2/J pattern. This will generate an event to update the pattern in the\n     * subscription state, so it's included in the next heartbeat request sent to the broker.\n     * No validation of the pattern is performed by the client (other than null/empty checks).\n     */\n    private void subscribeToRegex(SubscriptionPattern pattern,","sourceCodeStart":2231,"sourceCodeEnd":2267,"githubUrl":"https://github.com/apache/kafka/blob/c31c9215e131f8c17e79f8901b48c13ee6aa8e7a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java#L2231-L2267","documentation":"Thrown by subscribeInternal(Pattern, Optional) when the supplied java.util.regex.Pattern is null. The branch is selected because pattern == null in the condition `pattern == null || pattern.toString().isEmpty()`. Subscribing to a null pattern is meaningless, so the client rejects it before issuing a TopicPatternSubscriptionChangeEvent.","triggerScenarios":"Calling consumer.subscribe((Pattern) null); passing a Pattern field that was never assigned; a method that builds a Pattern from config and returns null when the config is missing; conditional code that calls subscribe(pattern) where pattern may be null.","commonSituations":"Configuration-driven subscriptions where the regex property is optional and resolved to null; refactoring from collection-based subscribe to pattern-based subscribe; test code passing null inadvertently; environment-specific setups that omit the topic pattern property in one environment.","solutions":["Guard the call: if (pattern != null) consumer.subscribe(pattern); else handle missing config explicitly.","Default the configuration to a sensible regex (e.g. \".*\") when the property is absent.","Fail fast at application startup if the required pattern property is missing rather than at runtime."],"exampleFix":"// before\nPattern p = props.get(\"topics.pattern\") != null ? Pattern.compile(props.get(\"topics.pattern\")) : null;\nconsumer.subscribe(p); // throws if property missing\n\n// after\nString patternStr = props.getProperty(\"topics.pattern\");\nif (patternStr == null || patternStr.isBlank()) {\n    throw new IllegalStateException(\"topics.pattern must be configured\");\n}\nconsumer.subscribe(Pattern.compile(patternStr));","handlingStrategy":"validation","validationCode":"// Before consumer.subscribe(pattern):\nif (pattern == null) throw new IllegalArgumentException(\"pattern must not be null\");\nObjects.requireNonNull(pattern, \"Pattern\");\nconsumer.subscribe(pattern);","typeGuard":"static boolean isNonNullOrEmptyPattern(Pattern p) {\n    return p != null && !p.toString().isEmpty();\n}","tryCatchPattern":"try {\n    consumer.subscribe(pattern);\n} catch (IllegalArgumentException e) {\n    if (e.getMessage().contains(\"cannot be null\")) {\n        log.warn(\"Null pattern supplied; skipping subscribe\", e);\n    } else throw e;\n}","preventionTips":["Build Patterns from validated configuration; reject null at config-load time.","Prefer Pattern.compile(validatedString) inside a helper that requires non-null input.","Treat subscribe(null) as a programming error, not a runtime fallback path."],"tags":["consumer","subscribe","pattern","validation","illegal-argument","java"],"analyzedSha":"c31c9215e131f8c17e79f8901b48c13ee6aa8e7a","analyzedAt":"2026-08-03T12:34:05.770Z","schemaVersion":2}