'Why Java SDK DriverManager.registeredDrivers takes instances from function registerDriver() instead of just using the instances created by Iterator?
I'm learning the Java SPI for JDBC driver.
in a simple word, jdk has an interface Driver, anyone can provider their own JDBC services impl, for example, mysqlJDBC, ProsgresJDBC.
Now when we try to use any service like getConnection(), DriverManager in sdk will scan all the Driver impl under META-INF folder and invoke each impl constructor. Invoking each impl class means loading the class file. During the class loading, all of the JDBC providers have a line in their class static block like
DriverManager.registerDriver(new Driver());
to put their created instance like ProgresDriver into a list field registeredDrivers.
Then jdk can call someDriver.connection() to get a conn.
My questions is, however, I realized the instances created by the ServiceLoader.Iterator.next() are not used anywhere.
try {
while (driversIterator.hasNext()) {
//my questions is here, jdk didn't take the return instance
driversIterator.next();
}
} catch (Throwable t) {
// Do nothing
}
while they provide a public method registerDriver() like above mentioned,
DriverManager.registerDriver(Driver toBeAddedDriver);
which basically add the instance into the registeredDrivers list
registeredDrivers.addIfAbsent(new DriverInfo(driver, da));
then why not jdk just use the instances created by the iterator like this?
try {
while (driversIterator.hasNext()) {
Driver nextDriver = driversIterator.next();
registeredDrivers.addIfAbsent(new DriverInfo(nextDriver, da));
}
} catch (Throwable t) {
// Do nothing
}
Is there anything I misunderstood? Thank you for explaining!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
