{"id":"ead96fa87e2b18ee","repo":"apache/kafka","slug":"topic-pattern-to-subscribe-to-cannot-be-empty","errorCode":null,"errorMessage":"Topic pattern to subscribe to cannot be empty","messagePattern":"Topic pattern to subscribe to cannot be empty","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 Pattern is non-null but its string form is empty (pattern.toString().isEmpty()). An empty pattern would match no topics (or, depending on regex engine, behave unexpectedly), so the client rejects it before sending a TopicPatternSubscriptionChangeEvent.","triggerScenarios":"Calling consumer.subscribe(Pattern.compile(\"\")); passing a Pattern built from a configuration property that resolved to an empty string; trimming/normalization that produced an empty regex.","commonSituations":"Configuration property defaulted to empty string instead of null; YAML/JSON config where the pattern key exists but value is blank; environment variable substituted to empty; UI/admin tooling that submits an empty field.","solutions":["Validate the source string before compiling: if (patternStr == null || patternStr.isBlank()) throw / default.","Provide a meaningful default regex when configuration is empty.","Add a startup assertion that the resolved pattern is non-blank."],"exampleFix":"// before\nString s = props.getProperty(\"topics.pattern\", \"\");\nconsumer.subscribe(Pattern.compile(s)); // empty string -> throws\n\n// after\nString s = props.getProperty(\"topics.pattern\");\nif (s == null || s.isBlank()) {\n    throw new IllegalStateException(\"topics.pattern must be a non-empty regex\");\n}\nconsumer.subscribe(Pattern.compile(s.trim()));","handlingStrategy":"validation","validationCode":"// Before consumer.subscribe(pattern):\nif (pattern == null || pattern.toString().isEmpty())\n    throw new IllegalArgumentException(\"pattern must be non-null and non-empty\");\n// or filter blank patterns out of any dynamic list before subscribing.","typeGuard":"static boolean isNonEmptyPattern(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 empty\")) {\n        log.warn(\"Empty pattern; no topics will match, skipping subscribe\", e);\n    } else throw e;\n}","preventionTips":["Validate pattern strings with a non-blank check before Pattern.compile.","Beware Pattern.compile(\"\") — it matches every topic; usually not intended.","Unit-test subscribe paths against empty-string and whitespace-only patterns."],"tags":["consumer","subscribe","pattern","validation","illegal-argument","java"],"analyzedSha":"c31c9215e131f8c17e79f8901b48c13ee6aa8e7a","analyzedAt":"2026-08-03T12:34:05.770Z","schemaVersion":2}