perlquestion
Ryszard
I have a daemon process which runs every n minutes. The daemon is persistent in memory and is executed via a while loop.
<p>During each iteration of the main code body, it must connect to a database, grab some data and do something with it (the details are not important for this discussion).</p>
<p>i was contacted this morning by our DBAs wrt to my application having 200 connections to the database, so i went and checked the code to see if i could find the connection leak.</p>
<p>to my utter surprise it was due to an undef statement.</p>
<p>to illustrate the way the daemon is created:
<code>my $app = Daemon->new(sleep => 60, mailLimit => 200);
while (1) {
$app->doSomething();
print scalar(localtime)." Sleeping 300 seconds...\n";
sleep 300;
}</code>
</p>
<p>inside the Daemon object is a call to create a database object (which creates the db connection) and assigns it to <code>$self->{dbo}</code></p>
<p>the code i use to create the database object checks for the existence of <code>$self->{dbo}</code>, and if it exists re-uses it, if not, creates it.</p>
<p>to force the creation of a new database object each time (for reasons i cant remember now - yes i should have used comments in the code :-) ) i did an undef on the <code>$self->{dbo}</code> variable.</p>
<p>the expected result is that once i undef the <code>$self->{dbo}</code> variable, it would fall out of scope and the database connection would be implicitly released.</p>
<p>in practice this is not the case. it seams that once the variable has been undef'd it is left dangling in memory and not cleaned up.</p>
<p>while this seems pretty black and white based on what i've observed, as mentioned, it was totally unexpected.</p>
<p>can anyone explain why?</p>