Exception Safety and Garbage Collection and Some Other Stuff<br />A Moderately Directed Rant<br />
Why should I care about this?<br />It’s very likely that you’ve been writing totally incorrect code without realizing it<b...
Boring Definitions<br />We need to define a couple basic things at the beginning so everybody’s on the same page<br />It’l...
More Boring Definitions<br />A resource is anything you need to return to the system once you’re done using it<br />File h...
Reasonable Code Example (C)<br />Let’s look at some C code so we can figure out what this talk is even about<br />voidexam...
Terrible Code Example (C++)<br />Let’s see that exact same code, but now we’ll pretend that it was compiled as C++<br />vo...
That Sucks!<br />Yes, it does suck! It’s such a problem that people were motivated to go try to solve it<br />BjarneStrous...
Modern Code Example (C++)<br />voidexample() {<br />Lockmy_lock(&g_mutex);<br />auto_ptr<int> my_int_pointer(new int());<b...
How RAII Actually Works<br />classLock {<br />private:<br />mutex* m_pMutex;<br />public:<br />Lock(mutex* pMutex) : m_pMu...
Sure, but I don’t use C++<br />That’s understandable. We are (for better or worse) a Java school, so let’s see if we can’t...
The Dispose Pattern (Java)<br />voidexample() {<br />IntegermyInteger = newInteger(0);<br />Locklock = newLock(g_mutex);<b...
More Dispose Loveliness (Java)<br />voidexample() {<br />FilemyFile = newFile(filename);<br />try {<br />DBConnectiondbCon...
Again, but with RAII (C++)<br />voidexample() {<br />FilemyFile(filename);<br />DBConnectiondbConn(credentials);<br />Lock...
One More Time (D)<br />voidexample() {<br />scopemyFile = newFile(filename);<br />scopedbConn= newDBConnection(credentials...
“You can take my deterministic resource management when my cold dead hand goes out of scope.” -- Anon<br />
Why does Java suck so bad?<br />By choice. You can have deterministic resource management alongside garbage collection, bu...
So what should I do?<br />My (unpopular) answer? Use C++ and Perl/PHP for everything until the D ecosystem matures a bit, ...
Okay, done ranting<br />I wish I had more helpful advice for Java, C#, Python, Ruby users, but this is the unfortunate sta...
Upcoming SlideShare
Loading in...5
×

Exception Safety and Garbage Collection and Some Other Stuff

15,331

Published on

It’s very likely that you’ve been writing totally incorrect code without realizing it. While not a full solution, this is an extremely informal attempt at an overview of the problem.

Published in: Technology
4 Comments
3 Likes
Statistics
Notes
  • For those of us 'stuck' with Java, have a look at 'lombok'. Specifically: http://projectlombok.org/features/Cleanup.html
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • @Are Tunes

    A finally block -always- gets executed. The purpose is to clean up resources regardless of whether a catch block exists or not (without a catch block, the exception bubbles to the callee, but just prior to the exception being thrown, any statements inside the finally block will be invoked).

    The finalize method (on the Object super class) is executed on the terms of the JVM. Is that what you're referring to?
    http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#finalize%28%29
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • There's no guarantee by the JVM that finally will ever run, just say'n
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • See also Go with its 'defer' and mostly deterministic error handling.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
15,331
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
73
Comments
4
Likes
3
Embeds 0
No embeds

No notes for slide

Exception Safety and Garbage Collection and Some Other Stuff

  1. 1. Exception Safety and Garbage Collection and Some Other Stuff<br />A Moderately Directed Rant<br />
  2. 2. Why should I care about this?<br />It’s very likely that you’ve been writing totally incorrect code without realizing it<br />Once you do realize it, it’s usually not too hard to fix the problem, depending on the language<br />This is information that isn’t all that widely known, for whatever reason<br />You can use it to show off at interviews!<br />You can use it to start arguments about which programming language is the best!<br />
  3. 3. Boring Definitions<br />We need to define a couple basic things at the beginning so everybody’s on the same page<br />It’ll be quick, I promise<br />Garbage collection is a method of managing dynamic (heap-allocated) memory<br />It’s non-deterministic, and there is usually no guarantee that memory is cleaned up at all<br />Most modern languages use garbage collection<br />
  4. 4. More Boring Definitions<br />A resource is anything you need to return to the system once you’re done using it<br />File handles, dynamic memory, locks, etc.<br />Exception safety means that you can throw an exception in the middle of your function without bad things happening<br />There’s a complicated formal definition with degrees of exception safety but this is good enough for our purposes<br />
  5. 5. Reasonable Code Example (C)<br />Let’s look at some C code so we can figure out what this talk is even about<br />voidexample() {<br />lock(&g_mutex);<br />int* my_int_pointer = (int*)malloc(sizeof(int));<br />do_something_with(my_int_pointer);free(my_int_pointer);<br />unlock(&g_mutex);<br />}<br />This is fairly reasonable, safe C code. It executes deterministically and everyone is happy<br />
  6. 6. Terrible Code Example (C++)<br />Let’s see that exact same code, but now we’ll pretend that it was compiled as C++<br />voidexample() {<br />lock(&g_mutex);<br />int* my_int_pointer = (int*)malloc(sizeof(int));<br />do_something_with(my_int_pointer);free(my_int_pointer);<br />unlock(&g_mutex);<br />}<br />Catastrophe! This is going to compile and run without warnings, but be completely and totally unsafe!<br />Why? Exceptions!<br />
  7. 7. That Sucks!<br />Yes, it does suck! It’s such a problem that people were motivated to go try to solve it<br />BjarneStroustrup (C++ language creator) came up with a solution which he named Resource Acquisition Is Initialization (RAII)<br />Incidentally, in addition to providing exception safety, RAII made C++ way easier to use<br />Let’s look at a correct C++ version of our code example, using RAII<br />
  8. 8. Modern Code Example (C++)<br />voidexample() {<br />Lockmy_lock(&g_mutex);<br />auto_ptr<int> my_int_pointer(new int());<br />do_something_with(my_int_pointer);<br />}<br />Thanks to RAII this example is exception safe, and we don’t have to worry about cleanup.<br />auto_ptr<T> is part of the C++ standard library, but we’ve just made up Lock<br />Let’s look at the code for our made-up Lock class so we can see how RAII actually works<br />
  9. 9. How RAII Actually Works<br />classLock {<br />private:<br />mutex* m_pMutex;<br />public:<br />Lock(mutex* pMutex) : m_pMutex(pMutex) { <br />lock(m_pMutex);<br /> }<br /> ~Lock() {<br />unlock(m_pMutex);<br /> }<br />};<br />In C++ a stack-allocated object’s destructor is always called once it goes out of scope, whether due to a function returning, due to normal code execution, or due to stack unwinding caused by a thrown exception<br />
  10. 10. Sure, but I don’t use C++<br />That’s understandable. We are (for better or worse) a Java school, so let’s see if we can’t make RAII work in Java<br />Immediately we run into some problems<br />Java doesn’t have destructors<br />Java doesn’t have stack allocation for objects<br />So RAII won’t work with Java, then. What else have we got?<br />For dynamic memory we have garbage collection, but that’s a special case of the problem that doesn’t really need (or provide) determinism<br />The best we can do is the Dispose pattern<br />
  11. 11. The Dispose Pattern (Java)<br />voidexample() {<br />IntegermyInteger = newInteger(0);<br />Locklock = newLock(g_mutex);<br />try {<br />doSomethingWith(myInteger);<br /> } finally {<br />lock.dispose();<br /> }<br />}<br />While rewriting this every time gives you exception safety, it’s really easy to forget it<br />If you forget to do this, your program will still compile and run with no warnings, despite being wrong. Awesome!<br />This is more verbose than even the C example, yet is the minimum amount of code required for Java<br />
  12. 12. More Dispose Loveliness (Java)<br />voidexample() {<br />FilemyFile = newFile(filename);<br />try {<br />DBConnectiondbConn = newDBConnection(credentials);<br />try {<br />LockmyLock = newLock(g_mutex);<br />try {<br />doSomething(myFile, dbConn);<br /> } finally {<br />myLock.dispose();<br /> }<br /> } finally {<br />dbConn.dispose();<br /> }<br /> } finally {<br />myFile.dispose();<br /> }<br />}<br />This is again the minimum code required to be correct<br />
  13. 13. Again, but with RAII (C++)<br />voidexample() {<br />FilemyFile(filename);<br />DBConnectiondbConn(credentials);<br />LockmyLock(&g_mutex);<br />doSomething(myFile, dbConn);<br />}<br />
  14. 14. One More Time (D)<br />voidexample() {<br />scopemyFile = newFile(filename);<br />scopedbConn= newDBConnection(credentials);<br />scopemyLock = newLock(g_mutex);<br />doSomething(myFile, dbConn);<br />}<br />
  15. 15. “You can take my deterministic resource management when my cold dead hand goes out of scope.” -- Anon<br />
  16. 16. Why does Java suck so bad?<br />By choice. You can have deterministic resource management alongside garbage collection, but the Java guys specifically chose not to<br />The D programming language supports RAII and has a garbage collector, so it’s definitely possible<br />Java, C#, Python, Ruby all screw this up to varying degrees<br />The latter three have some syntactic sugar for resource management, but the onus is still on you to remember to use it<br />Java 7 catches up with C# and adds the same syntactic sugar, but still doesn’t solve the problem<br />Perl, PHP, C++ and D all get it right to varying degrees<br />If PHP gets something right before your language does, you should reassess your life goals<br />
  17. 17. So what should I do?<br />My (unpopular) answer? Use C++ and Perl/PHP for everything until the D ecosystem matures a bit, then switch over to D entirely<br />C++ has its own set of problems, but it’s my opinion that they’re exaggerated and the benefits far outweigh them<br />If you’re stuck using a broken language like Java, I really don’t know what to tell you<br />I guess you could cry a little bit, but I don’t think it would solve the problem<br />Learn the Dispose pattern, always remember to use it<br />
  18. 18. Okay, done ranting<br />I wish I had more helpful advice for Java, C#, Python, Ruby users, but this is the unfortunate state we find ourselves in<br />If you want more information about anything mentioned:<br />The D Programming Language by Andrei Alexandrescu is an excellent D introduction<br />If you want to learn how to code modern C++, you should read Effective C++ by Scott Meyers<br />The Boost website has good information about exception safety and reference-counted smart pointers, which I didn’t really talk about (Scott Meyers does in Effective C++)<br />Google knows all<br />Questions?<br />
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×