Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Optimizing Code in Java

Cursus bekijken

Oefeninstructies

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

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

public class Main {
    public static void main(String[] args) {}
}

class Database {
	// Create a property for DatabaseClient
    private ____ ____
    
    public DatabaseClient getClient() {
    	// Lazily connect to our database
        if (client ____ ____) {
        	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) {}
}
Code bewerken en uitvoeren