question regarding JNI AttachCurrentThread

1,761 views
Skip to first unread message

ManDroid

unread,
Jan 24, 2012, 10:23:21 PM1/24/12
to android-ndk
I find myself needing to call back into the JVM from arbitrary native
threads that may or may not be long-lived. It's easy enough call
AttachCurrentThread prior to every Java method invocation on the
assumption that it's a (presumably fast) no op if the thread's already
attached, but I find myself wondering what the JVM does with attached
native threads when they go away somewhere in native-land without
being officially detached. Or in other words, is this going to be a
problem? If so, then I find myself wondering about the overhead of
attaching/detaching for each Java method invocation. Ideally each
thread would just register itself upon startup and detach on shutdown
but again, I'm writing code that must be callable from arbitrary
threads running code that has no idea it's running inside of Android,
so that's not a realistic option in this case.

Any thoughts on the matter?

Elliott Hughes

unread,
Jan 25, 2012, 2:28:37 PM1/25/12
to android-ndk


On Jan 24, 7:23 pm, ManDroid <glenn_axwor...@yahoo.com> wrote:
> I find myself needing to call back into the JVM from arbitrary native
> threads that may or may not be long-lived.  It's easy enough call
> AttachCurrentThread prior to every Java method invocation on the
> assumption that it's a (presumably fast) no op if the thread's already
> attached,

it is a fast no-op if the thread's already attached. i'll add a note
to http://developer.android.com/guide/practices/design/jni.html to
make this explicit.

> but I find myself wondering what the JVM does with attached
> native threads when they go away somewhere in native-land without
> being officially detached.  Or in other words, is this going to be a
> problem?

depends what you mean by "go away". hopefully
http://developer.android.com/guide/practices/design/jni.html answers
the question for both obvious interpretations of "go away".

Elliott Hughes

unread,
Jan 25, 2012, 2:33:02 PM1/25/12
to android-ndk


On Jan 25, 11:28 am, Elliott Hughes <e...@google.com> wrote:
> On Jan 24, 7:23 pm, ManDroid <glenn_axwor...@yahoo.com> wrote:
>
> > I find myself needing to call back into the JVM from arbitrary native
> > threads that may or may not be long-lived.  It's easy enough call
> > AttachCurrentThread prior to every Java method invocation on the
> > assumption that it's a (presumably fast) no op if the thread's already
> > attached,
>
> it is a fast no-op if the thread's already attached. i'll add a note
> tohttp://developer.android.com/guide/practices/design/jni.htmlto
> make this explicit.

actually, the documentation already says exactly what i would have
added, in exactly the place i would have added it!
Reply all
Reply to author
Forward
0 new messages