Tuesday, October 23, 2007

Closing FileStream and StreamWriter, and Garbage Collection

I came across this tidbit about the Close methods in FileStream and StreamWriter in an article by Jeffrey Richter: Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework. I was never really sure which Close to call and why, but this sums up whats going on behind the scenes:

FileStream fs = new FileStream("C:\\SomeFile.txt", FileMode.Open, FileAccess.Write, FileShare.Read);
StreamWriter sw = new StreamWriter(fs);
sw.Write ("Hi there");
// The call to Close below is what you should do
sw.Close();
// NOTE: StreamWriter.Close closes the FileStream. The FileStream
// should not be explicitly closed in this scenario

-

Notice that the StreamWriter's constructor takes a FileStream object as a parameter. Internally, the StreamWriter object saves the FileStream's pointer. Both of these objects have internal data buffers that should be flushed to the file when you're finished accessing the file. Calling the StreamWriter's Close method writes the final data to the FileStream and internally calls the FileStream's Close method, which writes the final data to the disk file and closes the file. Since StreamWriter's Close method closes the FileStream object associated with it, you should not call fs.Close yourself.


What do you think would happen if you removed the two calls to Close? Well, the garbage collector would correctly detect that the objects are garbage and the objects would get finalized. But, the garbage collector doesn't guarantee the order in which the Finalize methods are called. So if the FileStream gets finalized first, it closes the file. Then when the StreamWriter gets finalized, it would attempt to write data to the closed file, raising an exception. Of course, if the StreamWriter got finalized first, then the data would be safely written to the file.

How did Microsoft solve this problem? Making the garbage collector finalize objects in a specific order is impossible because objects could contain pointers to each other and there is no way for the garbage collector to correctly guess the order to finalize these objects. So, here is Microsoft's solution: the StreamWriter type doesn't implement a Finalize method at all. Of course, this means that forgetting to explicitly close the StreamWriter object guarantees data loss. Microsoft expects that developers will see this consistent loss of data and will fix the code by inserting an explicit call to Close.


So if you were wondering why your StreamWriter writes don't get committed to a file if you forget to call the Close method, that's the reason: it was designed that way.

Tuesday, February 27, 2007

Useful / Useless

The Google calculator helps me cook (google:"16 teaspoons in cups"), and do my daily combinatorics (google:"8 choose 6"). Full instructions here.

NYSC's entertainment channel, Clubcom, claims to have some website where you can give feedback, helping them choose music to your preferences. Something like mysportsclubsnetwork.com, sportsclubnetwork.com, etc. Whatever it is, I can never remember it exactly by the time I get back from the gym, and its not showing up on google. And I'm no idiot when it comes to google. What use is it making a website if there is no way to get to it? Don't be a cheapskate (wow, who uses that word?) and buy out the cybersquatters with your similar domain names and have them redirect to your site. And spread the word. People are stoops (wow, who uses that word?)
And while we're at it, lets outlaw, or at least do something mean to cybersquatters. (Any suggestions?) I love their holder pages... Like anyone is going to think, "Oh this is the wrong URL...But while I'm here, let me click here to get a free backgroud check and some viagra" ... I'm just bitter that foson.com is taken, thats all...

Tuesday, November 28, 2006

Haikus for Jews

Stolen from Haikus for Jews:

How soft the petals
of the floral arrangement
I have just stolen.
Left the door open
for the Prophet Elijah.
Now our cat is gone.
How can I atone
for scalping my tickets to
the High Holidays?


Why are we all about stealing packets of jam and maple syrup from brunch? I don't know, its just in our genes. Maybe one day we'll have no jam and 'll have no choice but to resort to using our well-stocked supplies.

Critical info for the NJ transplant

I used to be ashamed to tell people that I was from New Jersey, that is, until Garden State came out. Now I’m proud of my semi-suburban heritage. After moving to Manhattan, there was only one thing that I missed about NJ, the 7-Eleven. One of my earliest disappointments as a child was when the local 7-Eleven defected and recoined themselves "7-Twelve", selling Blurpees instead of Slurpees (I kid not). Happy was the day that 7-Eleven opened up on 23rd Street in Manhattan, yet it still does not show up on google maps (now there are 4 of them on the isle). So I mapped them with this great geocoding site, batchgeocode.com
Slurp away, just don't eat the strange, rotating meat-cheese things.

Thursday, November 16, 2006

Because the phone book is for losers.


After Google Local recently failed me (there is no Gap store at 625 6th Ave #3, Google, but don’t worry, I still love you), I went to maps.a9.com to verify another address Google gave me. A9 had this great feature that let you see street level photos of the storefronts in popular cities, like Manhattan, and take a virtual sideways stroll down the big streets. To my shock, surprise, and dismay, maps.A9 closed shop from pressure from bigger rivals. Rumor is that Google Earth will include full textured 3-d renderings of buildings which would definitely out-cool A9’s functionality.
On the plus side, I found a map site, alkemis that shows some potential, if only they throw in some more nifty features on top of mapping movies and live traffic cams.

Tuesday, November 14, 2006

Fire, Flee, Foes, Escape!


I kinda want one, but not badly enough to wait in line in the rain/cold for 10 minutes, let alone 8 hours. I'm just excited to see a lot of disappointed people, a lot of clamoring, pushing, and shoving, and a couple of servers being knocked down by the online rush. Nothing like a little good, ol'-fashioned, human-caused chaos. Do games teach violence? Can't wait to see how this weekend compares to your average soccer riot.

Wild, Wild WoW


I overheard one of the network guys at work claiming that subscribing to World of Warcraft has really saved him a lot of money. His gaming budget used to be $3000 a year, now he's only spending $200 on the subscription plus the occasional single player game here and there.
Yet another reason why I should join.


P.S. When is Wired going to stop talking about Second Life already?

Monday, November 13, 2006

I'd rather eat (like) a caveman

Still haven't had the time to go into a whole tirade about organics, but today I saw the Food Liberation Inc on my corner wants me to check out its "new Raw Foods section!!"
If we can find something positive from this summer's E.Coli-in-spinich scare, it could be that the public was once again made aware of the danger of bacterial contamination in vegetables. This isn't the first time this has happened; lettuce (2005) and alfalfa (1997) are among the others that have also been subject to bacterial outbreaks. You know what kills bacteria in foods? Cooking. "But what about the nutrients?!" raw food aficionados cry, "Think of the nutrients we lose by cooking!" Turns out that the beta-carotene in carrots and the lycopene in tomatoes are actually more readily absorbed after cooking. What about vegetables that you want raw, like lettuce? Well, the CDC has a suggestion, but those shopping for raw foods aren't going to like it: it's Irradiation. Scary word isn't it? But the FDA has deemed it so safe that foods don't even need to be labeled if irradiated.
The idea is simple: all electromagnetic radiation is basically the same phenomenon, whether its radio waves or light or x-rays; from the moment they are generated (by electricity, chemical reactions, or nuclear decay) they travel away from their source at the speed of light. Some can pass though us with no effect, like radio waves. Some can not, like visible light. Microwaves can cook by exciting molecules without disrupting them, generating heat. In irradiation, we are utilizing the ability of UV, X-rays, or Gamma rays to disrupt certain bonds in DNA. Biology is dependant on a chemical's precise structure, and when a structure is changed, its function is usually lost. Exposing the food to radiation damages bacterial DNA so that it can not replicate or express genes. It will also inactivate plant DNA, which will stop the plant from doing any more chemistry. DNA is not a nutrient; it just stores the codes for making proteins and replication; we don't lose anything by inactivating it. The radiation passes right through and can not be stored in the food any more than you can catch and store light. Yes, we must protect ourselves from being exposed to DNA damaging radiation (limit x-ray exposure [don't star in x-ray movies] and stay out of the sun), but we do not need to protect our foods. We do need to protect ourselves from food-borne illnesses in meats and vegetables and most importantly, we do need to protect ourselves from ignorance.

And cancer, stroke, heart-attacks, obesity...eat your veggies!

Tuesday, November 07, 2006

NYC: Dont Walk

NYC: Dont Walk
NYC: Dont Walk,
originally uploaded by wallyg.

Anyone know why Park Av is missing its Don't Walk signs in the high 40s, low 50s? I don't know exactly which intersections are missing the signs because they are also missing their street signs. I have two theories:
1. Its a ploy by the MTA to use the otherwise mostly useless, underused, $112 million dollar Northeast passage of Grand Central Terminal ?
or or or
2. Its part of the Waldorf=Astoria's grand plan to make visitors so afraid of stepping out of the hotel that they a. take a cab or bus tour anywhere they go or b. resign themselves to eating in the hotel? (How else could they get by on charging $19 for bagels and lox? )

What do you think? Are these actually crazy enough to work?

Do I have a chance at my lifelong dream of conspiracy-theory blogging?