Does assigning values to static member variables in a constructor cause any problems? (JAVA)

2189 views java
4

I am running two client programs. The clients need access to a common database.

I am using a Java class with static member variables as the database. Both clients have their own instance of the database class. I believe that the database's static member variables should, if modified, carry the changes to both database instances in the clients. Is this correct?

Additionally, the database's default constructor adds values to its static member variables. Is this bad practice, if so, why?

answered question

Please provide some code examples and more information what database you use and where the clients run. Do you have two different Java applications that run on the same machine or do you have one application that runs on two machines?

1 Answer

11

The static variables don't below to the instance of the class but to the class itself. Therefore both of your Client instances will be able to use the database without problems.

However, because they belong to the class and not the instance, attempting to access them before an instance has been created will cause your database variables to still be null and throw an exception if not caught.

Implementing a Singleton pattern might be a better way to solve your problem, example:

class Database {

    private static Database theInstance;

    private Database() {
        // Create connections here and stuff
    }

    public static Database getInstance() {
        if (theInstance == null) {
            theInstance = new Database();
        }
        return theInstance;
    }

}

Then you can access your database like this:

Database.getInstance().doQueryStuff(); // doQueryStuff is just an example of a method call.

posted this

Have an answer?

JD

Please login first before posting an answer.