Skip to content

Thread: make the thread-local map on first use - #65

Closed
duncanmcqueen wants to merge 1 commit into
ingelabs:masterfrom
duncanmcqueen:fix-thread-locals
Closed

duncanmcqueen wants to merge 1 commit into
ingelabs:masterfrom
duncanmcqueen:fix-thread-locals

Conversation

@duncanmcqueen

Copy link
Copy Markdown
Contributor

Split from #59.

Problem and fix

ThreadLocal uses Thread.locals, which a Thread constructor sets. Kaffe makes the Thread object of the main thread without a constructor: KaffeVM_attachFakedThreadInstance() in kaffe/kaffevm/thread.c calls newObject(ThreadClass) and sets the fields from C. It does not set locals. Thus each ThreadLocal on the main thread throws NullPointerException. Kaffe uses the same function for native threads that attach through JNI.

Classpath itself uses ThreadLocal during startup (VMAccessController), so Kaffe cannot start any program.

This change makes locals non-final, and Thread.getThreadLocals() makes the map when locals is null.

How to reproduce

This problem occurs only on a VM that makes Thread objects without a constructor. JamVM does not, so the test passes on JamVM with and without this change.

javac MainThreadLocal.java
kaffe MainThreadLocal
MainThreadLocal.java
/**
 * A ThreadLocal must work on the main thread. On Kaffe 1.1.x the main
 * Thread object is made without running a Thread constructor, so
 * Thread.locals is null.
 */
public class MainThreadLocal
{
  public static void main(String[] args)
  {
    try
      {
        ThreadLocal<String> t = new ThreadLocal<String>();
        t.set("value");
        boolean ok = "value".equals(t.get());
        System.out.println((ok ? "PASS" : "FAIL") + ": get() = " + t.get());
        System.exit(ok ? 0 : 1);
      }
    catch (Throwable e)
      {
        System.out.println("FAIL: " + e);
        e.printStackTrace(System.out);
        System.exit(1);
      }
  }
}

Results

Linux x86_64, ingelabs/classpath master (0406074), JamVM master, javac from JDK 8, autoconf 2.73, automake 1.19, the configure options of the CI Linux job, out-of-tree build. "Before" is master. "After" is master with this commit.

On Kaffe 1.1.10-pre, the last version in its repository (Haiku x86_64), with the Thread classes of master before glibj.zip, Kaffe stops before main():

Internal error: caught an unexpected exception.
Please check your CLASSPATH and your installation.
java/lang/ExceptionInInitializerError
   at java.lang.ClassLoader.getSystemClassLoader (ClassLoader.java:799)
caused by java/lang/NullPointerException:
   at java.lang.ThreadLocal.get (ThreadLocal.java:147)
   at java.security.VMAccessController.pushContext (VMAccessController.java:108)
   at java.security.AccessController.doPrivileged (AccessController.java:93)
   at gnu.java.nio.charset.Provider.provider (Provider.java:262)
   at java.nio.charset.Charset.provider (Charset.java:253)
   at java.nio.charset.Charset.charsetForName (Charset.java:208)
   at java.nio.charset.Charset.forName (Charset.java:188)
   at java.util.zip.ZipFile$PartialInputStream.<clinit> (ZipFile.java:528)
   ...

With this change: PASS: get() = value.

On JamVM (Linux): PASS: get() = value before and after.

Platforms

Not specific to Haiku, but specific to the VM. The problem occurs with Kaffe on all systems. Kaffe's repository is archived, so I cannot fix it in Kaffe.

I understand if you prefer not to have a workaround for one VM in Thread. The change is small, and it has no effect on VMs that run a Thread constructor.

AI assistance

An AI model (Claude Code, by Anthropic) wrote this change, the test and this text. The repository owner directed the work and checked the results. Please review it as you review other contributions.

🤖 Generated with Claude Code

Some VMs (for example Kaffe) make the Thread object of the main
thread without running a constructor, so its locals field is null and
every ThreadLocal fails. Make the field non-final and create the map
in getThreadLocals() when it is null.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: duncanmcqueen <dwmcqueen@gmail.com>
@guillerodriguez

Copy link
Copy Markdown
Contributor

Thanks for the detailed write-up and the reproducer.

I’m not sure Classpath is the right place to fix this, though. I think it’s a bug in Kaffe.

Classpath has a constructor for VMs to create Thread objects for threads that started outside Java, which is designed exactly for this use case: Thread(VMThread, String, int, boolean). Kaffe doesn’t use it, and instead sets a few instance fields from C. This is fragile, as this bug shows: any fields Kaffe doesn't known about are initialised to their default values. locals is one of them, threadId is another (so on Kaffe Thread.getId() also returns 0 for the main thread and for every JNI-attached thread). The same problem would also happen if Classpath adds any new fields to Thread in the future.

Also, the patch as it stands doesn’t cover every path. InheritableThreadLocal.newChildThread() and Thread.die() both read locals directly. So a thread created this way that never used a ThreadLocal would still get an NPE when it creates a child thread or when it dies. Those could be fixed, but they show that this approach works around one symptom at a time rather than the cause.

The proper fix here would be to modify KaffeVM_attachFakedThreadInstance() to something like this:

  • First create a VMThread object
  • Then construct the Thread calling the Thread(VMThread, String, int, boolean) constructor
  • Then set VMThread's back pointer to it

(the rest of the function can stay as it is)

That would fix locals, threadId and anything Classpath adds later, without VM-specific workarounds in Thread.

Also, you mention that Kaffe's repository is archived, so you cannot fix this in Kaffe. But if I understand correctly, you already maintain a set of Kaffe patches in order to add Haiku support. Perhaps that's the better place for this fix?

duncanmcqueen added a commit to duncanmcqueen/kaffe that referenced this pull request Oct 18, 2026
KaffeVM_attachFakedThreadInstance() made the Thread object of the main
thread (and of threads that attach through JNI) with newObject() and set
some fields from C. The fields that Kaffe does not know about kept their
default values. With GNU Classpath 0.99 (ingelabs), Thread.locals was
null, so each ThreadLocal on the main thread threw NullPointerException
and Kaffe stopped before main(). Thread.getId() also returned 0.

Use the Thread(VMThread, String, int, boolean) constructor that Classpath
has for threads that start outside Java, as createDaemon() already does:
make the VMThread, construct the Thread, then set the VMThread back
pointer. The rest of the function does not change.

Suggested by the GNU Classpath maintainer in ingelabs/classpath#65.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
duncanmcqueen added a commit to duncanmcqueen/bekaffe that referenced this pull request Oct 18, 2026
patches/kaffe/0004 is the fix that the GNU Classpath maintainer suggested
in ingelabs/classpath#65: KaffeVM_attachFakedThreadInstance() now uses
Thread(VMThread, String, int, boolean), as createDaemon() does. This
sets Thread.locals and Thread.getId() for the main thread. The same
commit is on the haiku branch of duncanmcqueen/kaffe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@duncanmcqueen

Copy link
Copy Markdown
Contributor Author

Thank you. I agree: the problem is in Kaffe, and your fix is better. I examined the points and they are all correct:

  • InheritableThreadLocal.newChildThread() and Thread.die() use locals directly, thus this pull request did not fix all the paths.
  • With Kaffe, Thread.getId() returned 0 for the main thread. I tested it: getId() = 0 before, also with this pull request.
  • Kaffe already uses your pattern in createDaemon() (kaffe/kaffevm/thread.c): it makes the VMThread, calls Thread(VMThread, String, int, boolean) and then sets the back pointer.

I changed KaffeVM_attachFakedThreadInstance() as you described, in my Kaffe fork: duncanmcqueen/kaffe@6de1bc046. The same patch is in BeKaffe (patches/kaffe/0004).

Results on Haiku R1/beta6 x86_64, with ingelabs master's Thread classes (without this pull request):

Test Kaffe before Kaffe with the fix
MainThreadLocal NullPointerException in ThreadLocal.get(), stops before main() PASS
Main thread: ThreadLocal, getId(), a child thread that inherits an InheritableThreadLocal and then exits (stops before main()) all pass, getId() = 1
Kaffe regression suite (149 tests) 137 or 138 pass (with this pull request, because without it nothing starts) 138 pass, with and without this pull request. The same tests fail as before (SecureRandomTest changes between runs)

The JNI path (AttachCurrentThread) also uses this function, but I could not test it: Kaffe's jthread_attach_current_thread() already aborts before it gets to this function, because it calls jthread_current() for a thread that is not attached yet. That is a different problem in Kaffe.

Thus I close this pull request. I also changed the description of #61.

An AI model (Claude Code, by Anthropic) made the Kaffe change and the tests, and wrote this text. I directed the work and checked the results.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants