Proposed API for JEP 259: Stack-Walking API

Peter Levart peter.levart at
Wed Nov 4 08:06:59 UTC 2015

On 11/03/2015 10:33 PM, Mandy Chung wrote:
>> On Nov 3, 2015, at 4:45 AM, Peter Levart <peter.levart at> wrote:
>> Hi Mandy,
>> Great API.
>> One thing I noticed is method StackWalker.getCallerClass() which is described as equivalent to the following:
>> walk((s) ->
>>                   .skip(2)
>> .findFirst()).orElse(Thread.currentThread().getClass());
>> ... the .orElse is presumably meant for the case when getCallerClass() is called directly from within method right? In that case Thread's implementation class is presented as the one doing the invocation of, which seems logical.
>> But what about if getCallerClass() is called from a method that has been invoked from native code via JNI in a newly attached thread that was not started in Java (like the main method)? We will also get the Thread's implementation class as the caller. Is this still logical?
> That should be Thread.class.

Yes, but is this always the right choice?

>> What would it be if getCallerClass() returned just Optional<Class<?>> and was left to the user to decide what to do in corner cases when there is no Java caller?
> I considered Optional<Class<?>>. I believe it is rare to have a JNI attached thread calling StackWalker::getCallerClass from native.  Most common cases will find a caller class.   Returning an Optional will force most common uses to handle the case if it’s absent.  It’s a tradeoff that I think it’s better to return Thread.class for the JNI attached thread calling getCallerClass in native which would rarely happen.

I was not thinking of calling StackWalker::getCallerClass from native, 
but calling some method from native, which then calls 
StackWalker::getCallerClass. The method itself can not anticipate how it 
will be called. Most methods calling getCallerClass will assume their 
caller is a Java method and won't bother to think of consequences when 
this is not the case. But any method can be called from native code in a 
newly attached thread. I'm not saying this is common, but can happen.

So the question is whether Thread.class is always the right substitute 
in such situations and whether it would be better to return null or 
Optional.empty(). If you don't want to force users to handle the 
uncommon case then perhaps it's best to return null. They will get NPE 
in the uncommon case and will be forced to handle it as opposed to using 
Thread.class which might silently "work", but not do the right thing.

Regards, Peter

>> So returning java.lang.Class objects is safe now there is jigsaw to enforce isolation when doing reflection on them. It's great to see how things fall together nicely.
> Yup.  I’m really looking forward to the strong encapsulation that strengthens the security.
> Mandy

More information about the core-libs-dev mailing list