Monday, June 21, 2004

Garbage Collection, RAII, and 'using'

If you fall exactly within the median range of computer programmers, then you've probably heard that "all modern languages use garbage collection", and you've taken to the idea with glee: you like the idea of having your garbage collected for you. However, you're probably also a little concerned that perhaps garbage collection is just a teensy bit less efficient than 'manual' memory management, although you'd never admit it in public (in case someone started forcing you to use malloc() and free() again).

On the other hand, you've probably not heard of RAII. If you have, you may know that it stands for "resource acquisition is initialization", although you're still not quite clear what that means. If it means anything.

If you do know about RAII, then you were probably extremely wary of the C# programming language - that is, until you discovered the 'using' statement. It's all good now, right?

To enlighten those who are at this point saying, "huh?", and to avoid (I hope!) a number of straw-man arguments, here's a brief summary of each of the terms in the title.

Garbage collection


Garbage collection is often referred to as "automatic memory management", although this can be a little misleading, as we'll see. The purpose of a garbage collector is to 'collect' blocks of memory that won't be used again and recycle them. The trick, of course, is knowing which blocks won't be used. There are several strategies for doing this, which I won't go into here. Generally, however, what happens is that allocated memory tends to stay allocated for a little longer than it otherwise would. This can lead to several efficiencies in the memory allocation scheme: most particularly, the malloc() function (or its equivalent) can be simplified enormously, as it no longer has to consider fragmentation problems. Generally speaking, this means that garbage collectors are more efficient for programs that allocate many small chunks of memory. Of course, the downside is that at any given moment, more memory is in use than is actually necessary - but then we're no longer trying to squeeze code, data and scratch space into 16k, are we?

Any actions carried out by an object at the point at which the garbage collector releases the memory allocated to it I will refer to as "finalization".

RAII


RAII is an idiom that has been floating around in C++ circles for some time now. The essential idea is that a resource (memory, file handle, database connection...) is acquired when an object is initialized (i.e. in the object's constructor). Conversely, the resource is released when the object is destroyed. The point of destruction is the interesting bit, and we'll have more on that later. However, suffice it to say that in C++, 'auto' or stack-allocated objects are destroyed as soon as they go "out of scope", meaning the variable that was bound to them when they were created is no longer accessible.

Generally when C++ programmers talk about RAII they're talking about wrapping up a resource in an object in such a way as to make certain guarantees about the way in which the resource will be used. In particular, they are used for exception safety: C++ does not have a 'finally' block. Bjarne Stroustrup explains why here.

There is an interesting twist to this story. It's possible to implement garbage collection using the RAII idiom (amongst other things). In fact, if you look here, you'll find an example of just such a thing. More commonly C++ programmers use a simpler reference-counting implementation often referred to as a "smart pointer". You can find a good one here. The good thing about a reference-counted implementation is that you can accurately predict when the object in question will be destroyed. What about cycles, you say? Consider weak references. I've found that they clarify my thinking on a number of issues revolving around ownership, lifecycles, and authority.

You can find out more about RAII here.

The 'using' statement


Here is where things get interesting. In C#, as in Java, the garbage collector makes no guarantees about when an object will be collected. C# supports 'destructors', but they're more accurately referred to as finalizers, since they are associated with the release of the memory rather than with the end of an object's useful lifecycle. This means that you can't use C# 'destructors' to manage resources as you can in C++. However, the C# team were aware of this, and they were also aware that Java-like try/finally constructs were bad: they involve a lot of typing, they make the code less readable, they detract from the purpose or intent of the code, and (and this is a big and) it's very easy for programmers -- even experienced ones -- to forget to use them.

The C# solution was to introduce a new construct: the using statement. This is essentially just shorthand for try/finally. When the scope of the using statement ends, the IDispose interface of the object that was 'used' is automatically called. This approach has two weaknesses. The first is minor: it limits the lifetime of the disposable object to the scope of a single statement. This is often not what we want. More serious, however, is the second objection: it still doesn't solve the problem of end-user forgetfulness. We're all human. We forget. We don't read the documentation. We often don't realise that we need to do anything other than just use the object we want to use. There's no safety net.

Some inferences


Here is a list of some of the things we can conclude from the preceding paragraphs:

  1. Garbage collection frees the programmer from having to use 'free'.

  2. Garbage collection is often more efficient than malloc/free.

  3. Garbage collection defers the point at which the memory is released, often indefinitely.

  4. What happens when the memory is released is called finalization.

  5. RAII relies on the timely destruction of objects to manage resources.

  6. RAII leads to easy-to-read ("intentional") code, with no need for try/finally or using statements.

  7. RAII makes exception safety very much easier.

  8. The using statement is really just try/finally in disguise.

  9. The end-user still needs to be told when to use 'using'.



Now we can say something interesting about the relationships between these concepts. Garbage collection (GC) solves the problem of memory management, whereas RAII solves the more general problem of resource management. GC uses the concept of "finalization"; RAII uses "destruction". "Using" is an attempt to bring the elegance and power of RAII into a GC context, but it's not much better than try/finally.

The problem, finally


Ideally, we would like to use both GC and RAII. Why can't we? Well, mostly because we can't be sure when a GC finalizer will run (if at all). This rules out the use of RAII in contexts where it's most useful -- mutex locks, for example. But why should we assume that the concepts of finalization and destruction are necessarily co-dependent? Destruction is the controlled, predictable end-of-life of an object. Finalization is the unpredictable point of memory-release. Surely these concepts are orthogonal?

Let's run with this a little further. We want controlled destruction, but we want to avoid getting the end-user involved in the details of when this should happen. One way of achieving these ends (in a language like Java or Python where [almost] all variables are by-reference) is through reference-counting. Reference-counted objects are almost garbage collected (except when they're involved in cyclical reference graphs), and they allow deterministic destruction. Since RAII objects tend not to refer to anything except the resource they represent, the problem of cycles is not really a significant one. Were objects with destructors implicitly subject to reference counting, and the destructor called when the reference count dropped to zero (the memory could be freed and the finalizer called at some later point), we'd have achieved the end of having both garbage collection and RAII in a single box.

The great thing about this solution is that it allows the programmers who design libraries to ensure that their objects won't be abused [too much]. The end-user doesn't have to remember that this particular object should have Dispose() or Close() (or whatever it is) called -- he just writes what comes naturally:

string[] getConfig() {

File f = new File("config.txt");
return f.readLines();
}


...and all is taken care of.

There are some wonderful things that can be done once this technique is admitted; there are also some gritty technical problems that have to be overcome. But that's a discussion for later.

21 Comments:

Blogger simonsays said...

http://www.jroller.com/page/komu/20040704#garbage_collection_vs_raii

6:57 PM  
Anonymous Anonymous said...

Predilection casinos? almost this sprouts [url=http://www.realcazinoz.com]casino[/url] advisor and cortege up online casino games like slots, blackjack, roulette, baccarat and more at www.realcazinoz.com .
you can also check our untrained [url=http://freecasinogames2010.webs.com]casino[/url] advert at http://freecasinogames2010.webs.com and overwhelm licit folding lower !
another late-model [url=http://www.ttittancasino.com]casino spiele[/url] procedure of events is www.ttittancasino.com , in compensation german gamblers, hang in there down on during dissatisfy nearing thither online casino bonus.

1:36 PM  
Anonymous Anonymous said...

[url=http://seghan.ru/go.php?sid=2][img]http://banners.servized.com/current/gif/pharm_720x90_1.gif[/img][/url]

[url=http://old-drugstore.net/]What is/are Zovirax Tablets?[/url]
What are acyclovir tablets or capsules?
ACYCLOVIR (Zovirax®) treats assured types of viral infections, specifically herpes infections. Acyclovir
pleasure not mend herpes infections; it will cure the sores restore faster and eschew to ease the pain or discomfort.
Sometimes acyclovir is conceded to improve prevent the infection from coming back. Acyclovir also treats shingles
and chickenpox infections. Generic acyclovir tablets and capsules are available.

What should I ascertain my health mindfulness provider in the vanguard I take this medicine?
They needfulness to know if you comprise any of these conditions:

•dehydration
•neurological infection
•kidney illness
•seizures (convulsions)
•an bizarre or allergic resistance to acyclovir, ganciclovir, valacyclovir, valganciclovir, other medicines, foods, dyes, or preservatives
•significant or disquieting to secure pregnant
•breast-feeding



[url=http://best-drugstore.aoaoaxxx.ru/][img]http://i079.radikal.ru/0910/b9/3f666eb40896.jpg[/img][/url]
























[url= ]buy Zovirax with saturday deliveryhow to get Zovirax prescription [/url]
Zovirax cod no prescription requiredZovirax with no perscription and delivered over night
[url= ]buy Zovirax overnight free deliverycheap Zovirax by money order [/url]
buy Zovirax online no prescriptionbuying Zovirax overnight delivery
[url= ]Cash on deliver Zovirax overnightZovirax Overnight COD no prescription [/url]
how to get prescription of ZoviraxZovirax purchase on line no prescription fast delivery
[url= ]order Zovirax cheap no membership fees no prescriptionZovirax no prescription next day delivery [/url]
buy Zovirax from a usa pharmacy without a prescriptionZovirax no doctors prescription
[url= ]buy Zovirax without a prescription overnight deliveryZovirax doctor consult [/url]
Zovirax ups delivery onlybuy Zovirax online without dr approval
[url= ]cash for Zoviraxhow to buy Zovirax with out a perscription [/url]
buy Zovirax medication codno rx needed for purchasing Zovirax
[url= ]buy Zovirax overnight deliverynext day delivery Zovirax with no script [/url]
Zovirax cod next day deliveryZovirax no prescription usa fedex shipping
[url= ]buying Zovirax online without prescriptionbuy cheap Zovirax without prescription [/url]
buy Zovirax no prescription codZovirax COD next day
[url= ]buy Zovirax cod next day fed exZovirax prescription from doctors online [/url]
online pharmacy cod Zoviraxbuy Zovirax next day delivery
[url= ]Zovirax non prescriptionorder Zovirax online by fedex [/url]
Zovirax online fed exus Zovirax fedex

2:52 PM  
Anonymous Anonymous said...

[url=http://seghan.ru/go.php?sid=35][img]http://s002.radikal.ru/i200/1001/f0/0ddd2280d906.jpg[/img][/url]












[url=http://members.multimania.co.uk/motluka/]buy discount cigarette online [/url]
where to buy cigarette rollers e cigarette where to buy it buy filter kools cigarettes online
[url=http://mitglied.multimania.de/mfoyjqw/]how many people buy cigaretts [/url]
buy e cigarettes in buy cigarette marlboro online cheap money order clove cigarettes
[url=http://mitglied.multimania.de/hnlgiui/]sites to buy cigarettes [/url]
buying cigarettes on carnival conquest buy cigarettes online with credit card age to buy cigarettes in florida
[url=http://mitglied.multimania.de/yaaysik/]buy discount cigarette [/url]
issues with buying cigarettes place to buy cigarettes buy cigarettes online indian
[url=http://mitglied.multimania.de/gdrzigo/]ny mail order cigarette [/url]
cigarette discount mail order where to buy cigarettes electric cigarettes buy
[url=http://mitglied.multimania.de/rehxicw/]buying cigarettes for minors [/url]
legal to buy cigarettes online buy cigarettes com buy cigarettes from an indian reservation
[url=http://usuarios.multimania.es/cmvaule/]marlboro cigarettes buy [/url]
buying cheap cigarettes buy tax free cigarettes online where to buy dse901 electronic cigarette

1:17 PM  
Anonymous Anonymous said...

in delivered this untrammelled of unfluctuating [url=http://www.casinoapart.com]casino[/url] ancillary at the greatest [url=http://www.casinoapart.com]online casino[/url] criterion with 10's of unceremonious [url=http://www.casinoapart.com]online casinos[/url]. participation of the mountains [url=http://www.casinoapart.com/articles/play-roulette.html]roulette[/url], [url=http://www.casinoapart.com/articles/play-slots.html]slots[/url] and [url=http://www.casinoapart.com/articles/play-baccarat.html]baccarat[/url] at this [url=http://www.casinoapart.com/articles/no-deposit-casinos.html]no shove off the mark casino[/url] , www.casinoapart.com
the finest [url=http://de.casinoapart.com]casino[/url] greater than the hugeness of UK, german and all unconventional the world. so in behalf of the orgasm [url=http://es.casinoapart.com]casino en linea[/url] discontinuity us now.

6:22 PM  
Anonymous Anonymous said...

You could easily be making money online in the underground world of [URL=http://www.www.blackhatmoneymaker.com]blackhat seo world[/URL], Don’t feel silly if you haven’t heard of it before. Blackhat marketing uses little-known or misunderstood avenues to build an income online.

11:08 PM  
Anonymous Anonymous said...

[url=http://flavors.me/sparkendperpternonlinel]Get Inderal No Prescription
[/url]

No Prescription
The Most Trusted Online Drug Supplier
Fast Worldwide Delivery
Cheapest prices for Inderal

dosage for inderal for migraine prevention
inderal for treatment of ptsd
Buy prescription cheap inderal propranolol
inderal withdrawl symptoms
inderal la essential tremor
inderal migraine treatment effective

[url=http://flavors.me/sparkendperpternonlinel]Approval inderal
[/url]
inderal sr
Inderal migraine prophylaxis
inderal la order online no prescription
inderal and cold feet

12:05 AM  
Anonymous Anonymous said...

Und dieser erste Schritt ist im Internet das Ansprechen mit der ersten Mail.
Glättung des Verdauungssystems Die enthaltenen Lotusblätter
sorgen für effektive Diurese, dadurch die Eingeweide sich entspannen
können. Jedoch das Schwierigkeit durch Diäten wie die Atkins Diät ist's, dass sie Sie setzen rein ernste Gefahr für Bluthochdruck und hohe Cholesterinwerte.

Here is my weblog; Www.English4Today.Com

3:21 PM  
Anonymous Anonymous said...

I realize that there is not a ton of variety in this list, since Rogue and i
- Net - Hack are essentially the same and Sorcerer #1 and #2 are more overtly the same.
You will eventually run into the Download Location menu with two options: Wii System Menu and SD Card.
Even when things seem hopeless, Kiko's narration provides some great comedy relief.

Also visit my site video downloader

2:11 PM  
Anonymous Anonymous said...

Ӏ was able to fіnd good іnformation from your content.



My ωeb blog ... click through the next website page

7:40 PM  
Anonymous Anonymous said...

Ι was аblе to fіnd gоoԁ іnformatiоn from your
contеnt.

my pagе :: click through the next website page
my web site :: http://www.porncrack7.com

7:40 PM  
Anonymous Anonymous said...

While it is one thing to have a social media profile on an online community
like Deviant - ART, it is a whole other thing
entirely to have fitted it with an effective SEO strategy.
If the executives promise high traffic then understand you are talking with a non-SEO person.
This is what professionals do. While you’re at it, remove all or fix 404 errors.
SEO must be implemented by following a step by step process.
The algorithms are not known publicly, but one thing is certain, is the search engine websites that the information is relevant to the purpose of the preferred site.
They make their strategy according to the audience their
client is targeting. When SEO services are working for you, you should always be ready to capitalise on innovations and fresh marketing opportunities.
Online research is required to determine
the packages and SEO Company. People these days use the Internet for a
varied purpose. organic search, frequency of blog posts, frequency of on-page optimization, the relative importance of links, the
use of social media, the best way to measure results, etc.

If the comments are created for solely promotional purposes, they will probably get deleted.
' Every page should be optimized with additional keywords. Here you will need an SEO agency such as Webfirm to try and run damage limitation. Once you find the right and affordable SEO Company, it is essential to talk about your business objectives, target customers and future goals with the professionals to help them develop their strategies accordingly. As of now, Thomas Lenarz has helped many people get the information on reputed SEO companies. Have you been looking at your competitor's
websites to see what kind of keywords they're using. However with passing time the complexity in this field has increased and performing an SEO task is not a simple thing to do. And make the work flow smoothly, using good grammar at all times. Yahoo style guide.

Feel free to visit my blog post; backlinkaufbau

11:37 PM  
Anonymous Anonymous said...

For some people, renting those games was another option, which yet again burns a
hole in their pocket. One way to test yourself is to
deal yourself hand after hand in front of a mirror and watch yourself as you react to the cards.
Even when things seem hopeless, Kiko's narration provides some great comedy relief.

Feel free to visit my blog kostenlos spielen ohne anmeldung

8:27 AM  
Anonymous Anonymous said...

It's not my first time to go to see this site, i am browsing this site dailly and get nice facts from here every day.

Also visit my blog post ... internetradio

2:51 PM  
Anonymous Anonymous said...

1. Once the number of back links will increase, web traffic flow will enhance.

The tools include efficient internet marketing,
proper usage of keywords, flawless content and creating social media buttons.
Naturally, they will flock to your competitor who does.
Since Google organic rank can bring in thousands of potential customers, search engine position service firms have made
a business of promising high positions in search engine results pages.
Search engines are getting smarter at detecting sites that are spamming keywords or made solely for the purpose of advertising.
Since keyword analysis is needed for both SEO (search engine optimization) and SEM, we often confuse using these terms.

Content writing for websites is not as simple as typing out
a predetermined amount of words, if you wish people to view the content.

Isn't that something you and your business should be a part of. Most of the XML sitemap generators online are simple enough for anyone to use. Thus, if your charges are overly cheap, this might cause doubts and worries from their mines regarding the quality of the service they get. Don't Forget to Replace the Default Favicon
with Your Logo. Let us assume that at this point you have 6 keywords.
Here you will need an SEO agency such as Webfirm to try
and run damage limitation. Once you find the right and affordable SEO Company,
it is essential to talk about your business objectives, target customers
and future goals with the professionals to help them develop their strategies accordingly.

Here are some examples of things that were once good moves that can now get you into trouble.
Law firms face various challenges and have issues in remaining at
the top in the market. SEO is becoming the most rewarding career nowadays.
The internet has become an integral part of our lives that according to the latest statistics, almost
1 billion Americans access the internet. Never post a half edited article, and never settle for
less than your best.

Visit my site ... www.compagnons-pierre.org

11:50 PM  
Anonymous Anonymous said...

Every member of this family should be examined by those who feel called by Moose as they are inter-related.
Many communities hold Earth Day celebrations that offer members of the community to participate in activities to benefit the neighborhood and also fun activities for children and adults.
The reflections of the sky, not only in the water,
but on the boat as well, lend a hand to a desired blending of color and a balance that is perfection.


Feel free to visit my page; Beauty

1:13 PM  
Anonymous Free Poker said...

I like to real your very interesting blog posts , they are very informative and most of it are cool.
--------------

latest news daily
Learn free holdem poker with Malay, New Zealand, Togo, Mongolia players
click me now
play poker and learn with best game to win real cash prizes
beginner service for new players
Become more serious poker player and win thousands of dollars.
darmowa gotówka do gry
Darmowy bonus bez depozytu dla gracza z Bulgaria, Swiss, Austria, Luxemburb.
holdem player guide
Buy a used or new laptop and learn with good poker school
make money instantly
Play texas holdem games with players from Panama, Venezuela, Kenya, RPA.
bonus senza deposito
Free starting capital and play Poker Ace, Titan, Party, Noble.
online texas poker
Receive token or real monye and play with other people online
poker online laptop
Wanna start poker career easy ? Start playing and learning today
texas holdem poker TV for poker Tv.

4:05 PM  
Anonymous Free Poker said...

I like to real your very interesting blog posts , they are very informative and most of it are cool.
--------------

latest news daily
Learn free holdem poker with Malay, New Zealand, Togo, Mongolia players
click me now
play poker and learn with best game to win real cash prizes
beginner service for new players
Become more serious poker player and win thousands of dollars.
darmowa gotówka do gry
Darmowy bonus bez depozytu dla gracza z Bulgaria, Swiss, Austria, Luxemburb.
holdem player guide
Buy a used or new laptop and learn with good poker school
make money instantly
Play texas holdem games with players from Panama, Venezuela, Kenya, RPA.
bonus senza deposito
Free starting capital and play Poker Ace, Titan, Party, Noble.
online texas poker
Receive token or real monye and play with other people online
poker online laptop
Wanna start poker career easy ? Start playing and learning today
texas holdem poker TV for poker Tv.

4:05 PM  
Anonymous Anonymous said...

Niсe replieѕ in retuгn оf
this quегy with firm argumеnts anԁ tellіng the whole thing conceгning
that.

Visit mу ωeb page weight loss shots hcg

5:20 AM  
Anonymous Anonymous said...

Sometimes seasons reasons some shoes might possibly be[url=http://niketrainersuksale.webeden.co.uk]Nike Blazers UK[/url]
temporarily do not possess the cabability to[url=http://tomscanadaoutlet.snappages.com]Toms Shoes Outlet[/url]
wear such shoes we all[url=http://addnikecanadastore.snappages.com]Nike Shoes Canada[/url]
properly place them[url=http://toplouboutinuksales.webeden.co.uk]Christian Louboutin Outlet[/url]
for the[url=http://louboutintrainersuk.blog.co.uk]Christian Louboutin Shoes[/url]
right put in order to avoid unnecessary harm to shoes[url=http://salelouisvuittonuk.webeden.co.uk]Louis Vuitton UK[/url]

Although if the insole is very bad, [url=http://cheapnikeblazersuk.webeden.co.uk]Nike Blazers UK[/url]
this might want to use a gentle brush and water gently scrub. To become noted that,[url=http://justlouboutintrainersuk.webeden.co.uk]Christian Louboutin Outlet[/url]
avoid using chemical cleaning agents cleaning, or they may increase the risk for insole the top of cloth off.[url=http://shoppradabagsuk.webeden.co.uk]Prada UK[/url]

7:18 PM  
Anonymous Anonymous said...

Additionally, it assumes there won't be fees regarding early pre-payment online bad credit loans. Dollars squandered impulsively purchases and also lottery passes is dream money, here today and also gone next week

I also feel that, in general, the united kingdom banks have not been as dangerous as their US counterparts and really should emerge relatively intact on the current sub-prime difficulty Before defaulting college loans happen, there's also deferment that happens 宝贝价格

4:02 PM  

Post a Comment

<< Home