Often dismissed silly things – System.out.println and e.printStackTrace

Java developers┬áhave affinity to use System.out.println and e.printStackTrace during the development phase. Some times developers forget to remove these two APIs, some times developers tends to dismiss them as silly things – due to which these two APIs would their way to production.

Whats wrong with it?

To answer this questions, lets review the code of System.out.println() (code is same in most of the Java implementations):

    public void println(String x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }

Are you noticing “synchronized (this)”? Here “this” refers to an instance of “PrintStream” object. Unfortunately there is only one instance of “PrintStream” object that is assigned to System.out for the entire JVM.

What does it mean to you?

Whenever you are going to invoke System.out.println anywhere in the code, it’s going to block. So more the volume your application starts to process more it’s going to block. More the response time would degrade. Besides having your debug statement spill over in the console, it’s going to hog your response time as well

Similar is the implementation in e.printStackTrace() API as well:

    private void printStackTrace(PrintStreamOrWriter s) {
        // Guard against malicious overrides of Throwable.equals by
        // using a Set with identity equality semantics.
        Set<Throwable> dejaVu =
            Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
        dejaVu.add(this);

        synchronized (s.lock()) {
            // Print our stack trace
            s.println(this);
            StackTraceElement[] trace = getOurStackTrace();
            for (StackTraceElement traceElement : trace)
                s.println("\tat " + traceElement);

            // Print suppressed exceptions, if any
            for (Throwable se : getSuppressed())
                se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);

            // Print cause, if any
            Throwable ourCause = getCause();
            if (ourCause != null)
                ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
        }
    }

Note the “synchronized (s.lock())”. Also printStackTrace() invokes “println” which is going to lock once again.

Bottom Line: Needless to say thing here – as you should have already inferred.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: