12

Does anyone know how much memory an Exception occupies once it is created and thrown?

For example, NullPointerException.

And how exceptions are being garbage collected?

Maxim Makhun
  • 2,197
  • 1
  • 22
  • 26
Bogdan T.
  • 668
  • 6
  • 13
  • 12
    They are collected just as any other Java object. Why would there be anything special about them? – Marko Topolnik Jan 10 '14 at 09:04
  • 6
    The size of an exception is going to depend on your Java implementation and the depth of the call stack. What do you need this information for? You probably shouldn't have a zillion exceptions lying around, so it won't matter most of the time. – user2357112 Jan 10 '14 at 09:06
  • 1
    I totally agree with Mark, that should be the answer to your question – Keerthivasan Jan 10 '14 at 09:09
  • 1
    I think the question for the garbage collection is kind of valid. Sure, an exception object is garbage collected after there is no more reference to it. But when is this condition reached? What is the livetime of the object? You don't traditionally assign it to a variable which scope is clearly visible. – André Stannek Jan 10 '14 at 09:25
  • If I have let's say a NPE having a call stack 20 levels deep and thrown 2000 times on Swing Thread, what effect would this have on the memory consumption. – Bogdan T. Jan 10 '14 at 09:25
  • @AndréStannek the scope is *entirely* visible. It gets assigned to a variable in the catch block. – Brian Roach Jan 10 '14 at 09:28
  • 1
    @BogdanT. It exists in memory until either it's caught and then falls out of scope / no more references are held, or it's uncaught and the main thread is halted due to the uncaught exception. – Brian Roach Jan 10 '14 at 09:30
  • @BrianRoach sure, it is visible but not as clearly as with any other variable. E.g. if the exception is re-thrown or wrapped the object would at least exists until the next catch block. Also it doesn't just start to exist in the catch block but in the throwing method where it is created. Just saying it might be a valid question to ask. – André Stannek Jan 10 '14 at 09:33
  • @AndréStannek that's no different than any other object. To wrap it you'd need to have caught it first then passed the reference to another exception. The only real magic involved is that your own code isn't holding a reference until you catch it. (Sort of, it's not much different than a return value except that it can implicitly travel up the call stack) – Brian Roach Jan 10 '14 at 09:36
  • I don't know exactly how big they are, but the stack trace is probably the biggest part. If you disable an exception's stack trace using the `writableStackTrace` argument to the constructor or by overriding `fillInStackTrace()` to do nothing, they should be very light. (As a bonus, disabling the stack trace makes construction very fast.) However, I can't imagine that memory costs of exceptions would be a problem. They go away quickly enough. If you want to avoid the GC overhead, just create one exception object statically, and throw it repeatedly. – Boann Jan 10 '14 at 09:39
  • This is like asking "how heavy is a barrel". Yeah that kind of depends on what you put in there. – Gimby Jan 10 '14 at 09:41
  • @BrianRoach exactly my point. An exception object can exist and not be applicable for garbage collection although it's not visibilly referenced in the code. Easily understandable once you think of it, but still a "special" case. – André Stannek Jan 10 '14 at 09:48
  • @AndréStannek fair point. – Brian Roach Jan 10 '14 at 10:46

5 Answers5

4

Does anyone know how much memory an Exception occupies once it is created and thrown?

That would depend entirely on the exception. Like any other object, it contains variable amount of data; the String message could be 4MB if someone did something silly:

Exception e = 
    new Exception(new String("Some gigantic message ... lalalalalalalalla"));

(Edit: ok, this is somewhat misleading; the exception contains a reference to a String and reference values are a fixed size, but the String itself might only be referenced by the exception - I changed it to be a non-literal to explicitly show it could be something that is collectible. A custom exception could hold anything though, it's an object like any other. In addition, it depends how far it has been thrown, since it holds the stack trace inside of it. There's a good Q/A here on SO; In java, what is the best way to determine the size of an object that covers this. )

And how exceptions are being garbage collected?

Just as any other object is. The Exception is thrown up the call stack and one of two things happen:

1) You catch it, and it's assigned to a variable in the catch block:

catch (Exception e) {

e now holds the one and only reference to the exception. When no more references to it exist (i.e. it either falls out of scope at the bottom of the catch block, or the object you pass it to gets collected, etc), it will get collected.

2) You don't catch it and it hits the top of the call stack for the current thread. At that point the exception falls out of scope so it will be collected, and the thread is of course halted.

** To be completely pedantic when I say "will get collected" I mean eventually as when an object in Java has no more references to it it's it's eligible for collection, and the GC deals with it.

Community
  • 1
  • 1
Brian Roach
  • 76,169
  • 12
  • 136
  • 161
1

Java Exceptions are Object so as any Other Objects the size depends by it structure if you have created a custom exception you can (for example) store e complete binary file other Object until you have free memory. You can set the initial and maximum space for your application. The free space change dynamically and now there is the GC question. Java Exceptions are Object so as any Other Objects garbage collection uses the rules in your Enviorment.

For a quick reference about exceptions http://docs.oracle.com/javase/tutorial/essential/exceptions/

this is an article about garbage collection where the key concept are

Summary on Garbage collection in Java

1) Java Heap is divided into three generation for sake of garbage collection. These are young generation, tenured or old generation and Perm area.

2) New objects are created into young generation and subsequently moved to old generation.

3) String pool is created in Perm area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM.

4) Minor garbage collection is used to move object from Eden space to Survivor 1 and Survivor 2 space and Major collection is used to move object from young to tenured generation.

5) Whenever Major garbage collection occurs application threads stops during that period which will reduce application’s performance and throughput.

6) There are few performance improvement has been applied in garbage collection in java 6 and we usually use JRE 1.6.20 for running our application.

7) JVM command line options –Xmx and -Xms is used to setup starting and max size for Java Heap. Ideal ratio of this parameter is either 1:1 or 1:1.5 based upon my experience for example you can have either both –Xmx and –Xms as 1GB or –Xms 1.2 GB and 1.8 GB.

8) There is no manual way of doing garbage collection in Java.

Read more: http://javarevisited.blogspot.it/2011/04/garbage-collection-in-java.html

If you use java 7 an intersting question about GC is this

Java 7 (JDK 7) garbage collection and documentation on G1

Other suggestion are useful if you need to view only the state bat if you need to tune the config of your app you need to work with GC alg end memory.

Community
  • 1
  • 1
user1594895
  • 587
  • 1
  • 10
  • 31
1

I'm wondering why nobody mentioned that the first thing which happens when you create an exception is that the stack trace is populated:

 public Throwable() {
    fillInStackTrace();
 }

If you create your own Exception class and override the fillInStackTrace() method to do nothing, your Exception will become just a simple Java Object and will occupy just as much memory as other objects (which have the same fields/values). But of course you will lose the most precious thing: the stack trace. As a conclusion, most of the memory occupied by the Exception object is due to storing the stack trace (it is stored in an internal format, then converted to StackTraceElement[] when the getStackTrace() method is called). So the larger the stack trace, the more memory the exception will occupy.

public class LightWeightException extends RuntimeException {

    public LightWeightException(String message) {
        super(message);
    }

    @Override
    public synchronized Throwable fillInStackTrace() {
        return this;
    }
}
Csa77
  • 649
  • 13
  • 19
0

Thats easy to find out by yourself. Launch jvisualvm and attach to the application you want to profile. Switch to the memory tab and filter for the exception you are looking for.

That should give you a good picture of how many bytes are used by exception objects - and also how this relates to your total heap size - and how well and how often they get collected.

light_303
  • 2,101
  • 2
  • 18
  • 35
0

Use Java Mission Control for checking this.

enter image description here

MariuszS
  • 30,646
  • 12
  • 114
  • 155