Proposed API for JEP 259: Stack-Walking API

Mandy Chung mandy.chung at oracle.com
Thu Nov 5 01:21:05 UTC 2015


> On Nov 4, 2015, at 12:21 AM, Peter Levart <peter.levart at gmail.com> wrote:
> 
>> 
>> 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.
> 
> ... additionaly, Thread.class (or a subclass) can not be reliably used as a sentinel value to identify such uncommon cases because it can sometimes be a legal caller, as in:
> 
> public class StackWalkerDemo {
> 
>     public static void doIt() {
>         StackWalker sw = new StackWalker(StackWalker.Option.CLASS_REFERENCE);
>         System.out.println("I was called from: " + sw.getCallerClass());
>     }
> 
>     public static void main(String[] args) throws Exception {
>         Thread t = new Thread(StackWalkerDemo::doIt);
>         t.start();
>         t.join();
>     }
> }

Good point.  If it returns null, users should prepare for it to return null.   So I think returning Optional<Class<?>> is better than null and that would make it equivalent to:
    walk(s -> s.map(StackFrame::getDeclaringClass).skip(2).findFirst());

I have changed the API to return that.

Will post an updated API and webrev once I incorporate most of the comments.

thanks
Mandy




More information about the core-libs-dev mailing list