CommencerCommencer gratuitement

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.

Cet exercice fait partie du cours

Optimizing Code in Java

Afficher le cours

Instructions

  • Create a property client of type DatabaseClient.
  • Lazily connect to our database.
  • Return our database client only when connected.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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) {}
}
Modifier et exécuter le code