Implementing lazy initialization
You're working on optimizing the startup time of a Java application. The team has identified that creating database connections eagerly is causing unnecessary delays. You need to implement lazy initialization, i.e., creating a connection only if there is none, for the Database
class to improve startup performance.
This exercise is part of the course
Optimizing Code in Java
Exercise instructions
- Create a property
client
of typeDatabaseClient
. - Lazily connect to our database.
- Return our database client only when connected.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
public class Main {
public static void main(String[] args) {}
}
class Database {
// Create a property for DatabaseClient
___
public DatabaseClient getClient() {
// Lazily connect to our database
if (___) {
client.connect("https//our-database.com");
}
// Return only when connected
return ___
}
}
// This class is simulating a real client connecting to a database
class DatabaseClient {
public void connect(String connectionUrl) {}
}