{"id":956,"date":"2026-11-05T13:53:00","date_gmt":"2026-11-05T12:53:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=956"},"modified":"2026-11-04T18:23:22","modified_gmt":"2026-11-04T17:23:22","slug":"simpledateformat-numberformatexception-multiple-points","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/simpledateformat-numberformatexception-multiple-points\/","title":{"rendered":"NumberFormatException: Multiple Points From a Shared SimpleDateFormat in Kotlin Coroutines"},"content":{"rendered":"<p>A NumberFormatException multiple points error from <code>SimpleDateFormat<\/code> means two threads parsed with one formatter at the same time. The formatter keeps its working state inside the instance. In a Kotlin app, that shared instance is usually a <code>val<\/code> in an <code>object<\/code> or a companion. Coroutines on <code>Dispatchers.Default<\/code> then call it from several threads at once. Each parse overwrites the other&#8217;s half-built number. The JDK page for <code>SimpleDateFormat<\/code> warns that date formats aren&#8217;t synchronized. A second cause keeps this bug alive. The repository takes an injected dispatcher. The unit test passes it a <code>StandardTestDispatcher<\/code>. That test runs every coroutine on one thread, so the race never happens there. Under light load the same code returns wrong timestamps without throwing. The fix is a <code>DateTimeFormatter<\/code>. That class is immutable and thread-safe. It&#8217;s native from API 26 and available below that through core library desugaring.<\/p>\n\n<h2>One shared formatter throws NumberFormatException multiple points<\/h2>\n\n<p>An orders screen loads 2,000 orders. Each has a <code>createdAt<\/code> string in UTC. The repository converts them to epoch millis in parallel, because the list is long.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">data class Order(val id: Int, val createdAt: String)\n\nobject DateParser {\n    private val format = SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss\", Locale.US).apply {\n        timeZone = TimeZone.getTimeZone(\"UTC\")\n    }\n    fun parseMillis(s: String): Long = format.parse(s)!!.time\n}\n\nclass OrderRepository(\n    private val dispatcher: CoroutineDispatcher = Dispatchers.Default,\n) {\n    suspend fun timestamps(orders: List&lt;Order&gt;): List&lt;Long&gt; = coroutineScope {\n        orders.map { o -&gt; async(dispatcher) { DateParser.parseMillis(o.createdAt) } }.awaitAll()\n    }\n}<\/pre>\n\n\n<p>We compiled this with Kotlin 2.4.20 and kotlinx-coroutines 1.11.0. We ran it on OpenJDK 25 on a 12-core machine. All 50 runs of the full list crashed. We then counted every failure over 300 rounds of the same parse. Most were <code>NumberFormatException: For input string<\/code> with a garbled number. These are a few of the others we saw.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">java.lang.NumberFormatException: multiple points\njava.lang.NumberFormatException: empty String\njava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 19\njava.lang.ClassCastException: class sun.util.calendar.Gregorian$Date cannot be cast\n    to class sun.util.calendar.JulianCalendar$Date<\/pre>\n\n\n<p>The <code>multiple points<\/code> trace never reaches your own code in its top frames.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">at java.base\/jdk.internal.math.FloatingDecimal.checkMultiplePoints\nat java.base\/java.lang.Double.parseDouble\nat java.base\/java.text.DigitList.getDouble\nat java.base\/java.text.DecimalFormat.parse\nat java.base\/java.text.SimpleDateFormat.subParse\nat java.base\/java.text.SimpleDateFormat.parse<\/pre>\n\n\n<p>It fails in the JDK&#8217;s number parsing. That makes it easy to blame bad server data. The exact messages come from the OpenJDK implementation. A device can word them differently. The cause stays the same.<\/p>\n\n<h2>Root cause one is the parse state stored inside SimpleDateFormat<\/h2>\n\n<p>A <code>SimpleDateFormat<\/code> holds a <code>Calendar<\/code> and a <code>NumberFormat<\/code> as fields. The <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.base\/java\/text\/DateFormat.html\" target=\"_blank\" rel=\"noopener\"><code>DateFormat<\/code> reference<\/a> lists both as protected fields of the base class. Each <code>parse<\/code> call writes the fields it reads into that shared <code>Calendar<\/code>. It also runs the digits through the shared number parser. Two threads in the same call overwrite each other&#8217;s partial results. One thread&#8217;s digits land in the other&#8217;s buffer. That&#8217;s how a date string ends up as &#8220;multiple points&#8221; or an empty number.<\/p>\n\n<p>The <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.base\/java\/text\/SimpleDateFormat.html\" target=\"_blank\" rel=\"noopener\">Java SE 21 <code>SimpleDateFormat<\/code> reference<\/a> says date formats are not synchronized. It recommends a separate instance per thread, or external synchronization. The <a href=\"https:\/\/developer.android.com\/reference\/java\/text\/SimpleDateFormat\" target=\"_blank\" rel=\"noopener\">Android reference for the same class<\/a> carries the same warning. Putting the formatter in an <code>object<\/code> makes it one instance for the whole process. Every caller shares it.<\/p>\n\n<p><code>Dispatchers.Default<\/code> turns that sharing into a real race. Its <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines\/-dispatchers\/-default.html\" target=\"_blank\" rel=\"noopener\">reference<\/a> says it uses as many threads as there are CPU cores, with a minimum of two. So even a low-end phone can run two parses at once. Each <code>async<\/code> above can land on a different worker thread.<\/p>\n\n<p>A crash is at least visible. We also ran the repository 20,000 times on just two orders at a time. That&#8217;s closer to a real screen, where only a couple of parses overlap. 43 rounds crashed. 634 timestamps came back wrong with no exception at all. Those orders would show the wrong date or sort in the wrong place. Nothing would reach your crash reporter.<\/p>\n\n<h2>Root cause two is a test dispatcher that runs everything on one thread<\/h2>\n\n<p>The repository takes a dispatcher so it can be tested. That&#8217;s good practice. The test then passes the dispatcher that <code>runTest<\/code> expects.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@Test\nfun parsesAllTimestamps() = runTest {\n    val repo = OrderRepository(StandardTestDispatcher(testScheduler))\n    val result = repo.timestamps(orders)\n    assertEquals(orders.map { expectedMillis(it) }, result)\n}<\/pre>\n\n\n<p>This test passes every time. We ran it against the broken parser. All 2,000 timestamps were correct. The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-test\/kotlinx.coroutines.test\/run-test.html\" target=\"_blank\" rel=\"noopener\"><code>runTest<\/code> reference<\/a> explains why. The test runs on a single thread unless child coroutines use another dispatcher. Child coroutines don&#8217;t run in parallel with the test body. So the 2,000 <code>async<\/code> blocks run one after another. One at a time is exactly the use <code>SimpleDateFormat<\/code> supports.<\/p>\n\n<p>Two causes stack here. The shared formatter makes the code unsafe. The single-threaded test makes it look safe. A test on real threads would only catch the race when the timing happens to line up. So fixing the test alone gives you a flaky test. The real fix is a formatter that has no shared state to race on.<\/p>\n\n<h2>An immutable DateTimeFormatter fixes it in the same object<\/h2>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">object DateParser {\n    private val format = DateTimeFormatter.ofPattern(\"yyyy-MM-dd'T'HH:mm:ss\", Locale.US)\n\n    fun parseMillis(s: String): Long =\n        LocalDateTime.parse(s, format).toInstant(ZoneOffset.UTC).toEpochMilli()\n}<\/pre>\n\n\n<p>The <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.base\/java\/time\/format\/DateTimeFormatter.html\" target=\"_blank\" rel=\"noopener\"><code>DateTimeFormatter<\/code> reference<\/a> states the class is immutable and thread-safe. Parsing doesn&#8217;t write to the formatter, so one shared instance is fine. The time zone moves out of the formatter. <code>ZoneOffset.UTC<\/code> now says it explicitly at the conversion. We ran the fixed parser 50 times on the full list on <code>Dispatchers.Default<\/code>. There were no crashes and no wrong timestamps.<\/p>\n\n<p>On Android, <a href=\"https:\/\/developer.android.com\/reference\/java\/time\/format\/DateTimeFormatter\" target=\"_blank\" rel=\"noopener\">DateTimeFormatter<\/a> was added in API level 26. If your <code>minSdk<\/code> is lower, turn on core library desugaring. The <a href=\"https:\/\/developer.android.com\/studio\/write\/java8-support\" target=\"_blank\" rel=\"noopener\">Java 8 support page<\/a> lists a subset of <code>java.time<\/code> among the APIs it provides. This Gradle setup follows the sample on that page.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ app\/build.gradle.kts\nandroid {\n    compileOptions {\n        isCoreLibraryDesugaringEnabled = true\n    }\n}\n\ndependencies {\n    coreLibraryDesugaring(\"com.android.tools:desugar_jdk_libs:2.0.3\")\n}<\/pre>\n\n\n<p>Two other fixes also stopped the crash in our runs. A <code>@Synchronized<\/code> parse function had no failures. It also makes the parallel parse run one at a time. A <code>ThreadLocal&lt;SimpleDateFormat&gt;<\/code> also had no failures, at the cost of one formatter per worker thread. Both are acceptable in legacy code you can&#8217;t migrate yet. Neither is better than the immutable type. If your dates are plain ISO-8601 instants with a <code>Z<\/code>, <code>Instant.parse<\/code> needs no formatter at all.<\/p>\n\n<p>The <a href=\"https:\/\/grindloop.ai\/blog\/string-format-locale-numberformatexception\/\">String.format locale bug<\/a> throws the same <code>NumberFormatException<\/code> for a different reason, the device locale. The round itself is scored past the first fix. Hass covers that in <a href=\"https:\/\/grindloop.ai\/blog\/android-debugging-interview-second-bug\/\">finding the bug and still not passing<\/a>.<\/p>\n\n<h2>How to explain it in a debugging round<\/h2>\n\n<p>The interviewer may show only the stack trace and ask what&#8217;s wrong with the date. Start from the message, then reach the second cause.<\/p>\n\n<ol>\n<li>Read the trace. It fails inside <code>DecimalFormat<\/code> from <code>SimpleDateFormat.subParse<\/code>. The input string itself is valid.<\/li>\n<li>Name the shared state. One <code>SimpleDateFormat<\/code> lives in an <code>object<\/code>. It stores its <code>Calendar<\/code> and number parser as fields.<\/li>\n<li>Name the concurrency. <code>async<\/code> on <code>Dispatchers.Default<\/code> runs parses on several threads at once.<\/li>\n<li>Say what&#8217;s worse than the crash. Under light overlap, it returns wrong dates with no exception.<\/li>\n<li>Explain why tests pass. <code>runTest<\/code> with an injected <code>StandardTestDispatcher<\/code> runs every coroutine on one thread.<\/li>\n<li>Give the fix. Use <code>DateTimeFormatter<\/code>, plus desugaring below API 26. Mention <code>@Synchronized<\/code> or <code>ThreadLocal<\/code> as fallbacks with their costs.<\/li>\n<\/ol>\n\n<h2>Fixes that look right and still race<\/h2>\n\n<ul>\n<li>&#8220;Move it to <code>Dispatchers.IO<\/code>.&#8221; The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines\/-dispatchers\/-i-o.html\" target=\"_blank\" rel=\"noopener\"><code>Dispatchers.IO<\/code> reference<\/a> says it shares threads with <code>Default<\/code>. It allows even more of them. All 30 of our runs on IO crashed.<\/li>\n<li>&#8220;Mark the field <code>@Volatile<\/code>.&#8221; That only makes the reference visible across threads. The formatter&#8217;s internal fields still race. All 30 of our runs crashed.<\/li>\n<li>&#8220;Catch the exception and return <code>null<\/code>.&#8221; The crash goes away. The silent wrong timestamps stay. Some dates are now missing too.<\/li>\n<li>&#8220;The server sent a bad date.&#8221; The same string parses correctly when the code runs on one thread.<\/li>\n<li>&#8220;The tests pass, so the parser is fine.&#8221; The test ran every coroutine on one thread. It never exercised the race.<\/li>\n<\/ul>","protected":false},"excerpt":{"rendered":"<p>NumberFormatException multiple points means one SimpleDateFormat raced across coroutine threads. Why runTest hides it, the silent wrong dates, and the fix.<\/p>\n","protected":false},"author":2,"featured_media":957,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"NumberFormatException: Multiple Points From a Shared SimpleDateFormat in Kotlin Coroutines","rank_math_description":"NumberFormatException multiple points means one SimpleDateFormat raced across coroutine threads. Why runTest hides it, the silent wrong dates, and the fix.","rank_math_focus_keyword":"numberformatexception multiple points","footnotes":""},"categories":[9,7],"tags":[15,70,13,87,16,12,72,45],"class_list":["post-956","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bug-squash","category-java","tag-android","tag-concurrency","tag-coroutines","tag-debugging-interview","tag-interview-prep","tag-kotlin","tag-race-condition","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/956","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/comments?post=956"}],"version-history":[{"count":1,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/956\/revisions"}],"predecessor-version":[{"id":958,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/956\/revisions\/958"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/957"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=956"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=956"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=956"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}