In a pdf doc[1] recently mentioned, an example repeatedly attach and detach a
thread, in a callback wrapper. However, fadden, you say[2] that you're "not a
fan of perpetually attaching and detaching native threads".
I suppose that it can indeed be heavy. The point is that it has the advantage of
being very transparent. There's nothing special to do when creating or
destroying the thread.
However, in order to avoid such repeated calls to Attach/DetachCurrentThread(),
I am thinking about a thread create/destroy wrapper API. For consistency I might
want to use this wrapper wherever I'm currently using pthread calls. This would
result in all native threads being attached, be it necessary or not.
But I'm worried about how that could affect performance.
What are the consequences of attaching a thread to the VM? Will it have more
chance to get interrupted (by the GC, etc..)? Will this increase memory usage?
Any other side-effect?
TIA
[1] http://android.wooyd.org/JNIExample/files/JNIExample.pdf
[2] http://bit.ly/cS9Vwo
--
Olivier
Indeed, if attaching a thread allocates an object, I can see why you don't like
the idea of repeatedly attaching/detaching a thread. That could cause a lot of
garbage collection.
> Any thread in "native" state is ignored by the GC. If the thread
> makes a JNI call, the VM does a check for suspension at that point.
>
> The one area where you do need to be careful is that you need to
> detach the thread (with DetachCurrentThread) before the thread exits.
> Attach/Detach don't stack, so you can Attach all you want (it's a
> convenient way to get the JNIEnv if you don't want to manage it) and
> just call Detach once at the end. If you're targeting 2.0+, you can
> use a pthread_key_create destructor function to have it happen
> automatically.
That sounds good. Sure, detaching, this is what the wrapper I mentioned is
about, by wrapping the start routine. And calling AttachCurrentThread is indeed
handy to retrieve the JNIEnv.
Thanks
--
Olivier