Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Static Classes and Multi-Threads

Status
Not open for further replies.

phatening

Programmer
Aug 8, 2005
18
US
Hi all,

I have a multi-threaded environment.

I have a JDBC class that connects to the database.

I also have a class called, Query, that has static methods and a static instance variable of the JDBC class.

Each method executes a specific SQL statement and it uses the JDBC static instance variable to connect to the database.

My Questions:
1) Does it help or hurt performance that my Query class is static and threads do not have to instantiate new instances of Query.
2) Should I make methods of my JDBC class static as well?
3) Is there any performance difference if the static methods in my Query class is using static instance variables.

I greatly appreciate the help.

Thanks,
Spence
 
static variables and instances mean there are only once instance in the JVM - so in theory, I believe it should be more efficient, because in effect there is only one version of an object on the heap - each access of that instance is just referencing a pointer in memory rather than allocating more memory.

However, and this is extremely important, if you have multithreaded code accessing static variables or objects, then you must ensure that access to those variables is synchronized, and that methods are re-entrant (ie, do not rely on global variables outside of those methods), or your code could have unexpected outcomes.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Using static methods tends to get in the way of some of the good design principles of OO. They can't be defined in an interface, for example. This makes classes using them hard to test since you can't use them in an interface which could be implemented by a mock class.

In your case, if you decided you wanted to provide 'Query' functionality in variety of different forms, you might want that Query class as an interface, with implementations for all the different functionality. Having statics in it will prevent that.

Tim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top