Re: Lazy initialization
Sreenivas wrote:
import java.util.ArrayList;
import java.util.List;
public class Book
{
private String ISBN;
private String Title;
private String Author;
private float Price;
public Book(String ISBN)
{
this.ISBN = ISBN;
}
public String getBookName()
{
return Title;
}
public List<Book> getBooks()
{
List<Book> books = new ArrayList<Book>();
//Here goes code for making database connection and loading Book
objects
//into ArrayList
return books;
}
}
Now i have a couple of questions.
When is books (ArrayList ) object created ? I mean, is it created
the moment
i create Book object( Book book = new Book() ) or when i call getBooks
() method on Book object?
When you execute:
new ArrayList<Book>()
Is it fine to place getBooks() method in Book class? or i need to
create an antoher class
place getBooks() method in that class?
I would suggest another class.
I have a difficulty in understanding Lazy Initialization .
Lazy Initialization:
Lazy Initialization for List<Book> in getBooks() method is like this ,
if i am not wrong
public List<Book> getBooks()
{
List<Book> books;
if(books==null)
{
books = new ArrayList<Book>();
//Here goes code for making database connection and loading Book
objects
//into ArrayList
}
return books;
}
No.
Lazy loading is when reading the books when getBooks is called and
not at startup.
It can also mean loading books now but wait loading other objects
inside Book until they are needed - but that is not relevant here.
BTW, I do not think the above compiles - books is not initialized.
If getBooks () method is requested and books variable is null
( doesn't exists in memory) then a new ArrayList<Book> is
created,populated with Book objects and returned.if books variable is
not null(presumably pointing to list of books)
then no database connection is made and List of books is returned.
In this way i am just preventing making of multiple database
connections for each request of getBooks().
That can also be implemented. It is caching.
If i don't use Lazy Initialization then i am making database
connection for each request of getBooks() method.
So, is my above explanation is right about Lazy Initialization?
Please point me in right direction, if i am wrong.
You should get a connection from a connection pool every time
you need to access the database.
> BTW, this is where i am reading about lazy Initialization
> http://martinfowler.com/eaaCatalog/lazyLoad.html
Rather brief on the web.
Arne