简体   繁体   中英

What is the meaning of `int dummy` in the fillInStackTrace() method in Java?

private native Throwable fillInStackTrace(int dummy);

This method is called with dummy=0 when an Exception is created. What is the meaning of dummy ? Is it the depth of the stack trace to construct?

Update:

public class MyEx extends RuntimeException{
   
    @Override
    public synchronized Throwable fillInStackTrace() {
        Method method = null;
        try {
            Class<?>[] classArray = new Class<?>[1];
            classArray[0] = int.class;
            method =Throwable.class.getDeclaredMethod("fillInStackTrace", classArray);
            method.setAccessible(true);
            Object obg = method.invoke(this, 6);

            StackTraceElement[] trace = ((MyEx) obg).getStackTrace();
            System.out.println();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return this;
    }
}

It seems that dummy is really dummy, it doesn't matter what value I put in, the result will be the same...

I wanted to limit the stack trace size to 3 to consume less memory and also creating exceptions would be faster from an execution point of view. I have a real use case where I need many exceptions but with shallow stack traces.

It doesn't mean anything. It is a dummy argument.

The native code implementation completely ignores the argument. For example, in OpenJDK 11, the bridge method implementation is as follows:

/*
 * Fill in the current stack trace in this exception.  This is
 * usually called automatically when the exception is created but it
 * may also be called explicitly by the user.  This routine returns
 * `this' so you can write 'throw e.fillInStackTrace();'
 */
JNIEXPORT jobject JNICALL
Java_java_lang_Throwable_fillInStackTrace(JNIEnv *env, 
        jobject throwable, jint dummy)
{
    JVM_FillInStackTrace(env, throwable);
    return throwable;
}

As you can see, the dummy argument is ignored.


If you are looking for a way to limit the depth of a stacktrace, the supported way to do this is to use the -XX:MaxJavaStackTraceDepth=depth option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM