O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Function Values and the Loan Pattern

Suppose you have a Resource class:

 class​ Resource {
  println(​"Creating Resource"​)
 
 def​ someop1() { println(​"someop1"​) }
 def​ someop2() { println(​"someop2"​) }
 
 def​ close() { println(​"cleaning-up..."​) }
 }

If an instance of Resource takes up significant resources outside the JVM, like database connections, open files, handles to external systems with significant memory usage, and so on, you’d want to clean up the resource quickly after use. You can’t rely on the JVM’s garbage collector (GC), as you can’t predict when it would run, and your memory usage within the JVM may be too low to trigger the GC reasonably soon to clean up the external resources. Users of your class may be tempted ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required