Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why we require Class.forName() multiple times

 
as chhipa
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear all,
I read in books that Class.forName("driverClass") loads the jdbc driver in java virtual machene and Driver.getConnection("url") establishes connection to the database.

My question is if I have two jdbc programs to interact with the same database why do I need to Class.forName("driverClass") in both the programs.
Instead I could use Class.forName("driverClass") in first program and Driver.getConnection("url") in both the programs because the driver class is already loaded in the JVM through the first program.
 
Scott Johnson
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Class.forName() registers the driver in the current JVM process and it stays registered in that process until it terminates.

It does not register the driver globally on the computer for all processes to see. The registration does not have any effect outside that single process.

You mention that you have two programs. I assume that means each program is running in it's own JVM process. The two processes are independent of each other. What is registered in one process is not visible in the other. Each program will need to register the driver within it's instance of the JVM.

Am I explaining this clearly?
 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well see Class.forName() method load the driver for current running instance only not globaly so you need two class.forName() method to load driver
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic