Re: Confusing facts...
getsanjay.sharma@gmail.com wrote:
? What is the actual difference between "import com.mysql.jdbc.driver"
and Class.forName("com.mysql.jdbc.driver") if in the end what they
both do is load the class ? Why is the second one used for Database
code?
Import doesn't actually create any code. By convention, JDBC drivers
install themselves into java.sql.DriverManager in their static
initialiser. In order to load a class use Class.forName (the one
argument variant, or the three argument variant with true) or just use
the class in some way.
Instead of using Class.forName and DriverManager, you can use the driver
directly. In fact, if you were going to hardcode the driver name in your
Class.forName statement, you might as well just use the driver directly
- much less fuss.
? What is the real difference between the run() and start() method of
Thread? [...]
If you call run directly, there is no point in using Thread. You don't
create actually thread. You just run the task to completion then carry
on with the calling thread. With Thread.start the task runs in parallel
with the calling thread.
Thread should never have implemented Runnable. You can prevent
Thread.start/run accidents by always using a subclass of thread that
detects the problem:
public final class SafeThread extends Thread {
/**
* Indicates whether {link Thread#run} has been invoked.
*/
private final java.util.concurrent.atomic.AtomicBoolean run =
new java.util.concurrent.atomic.AtomicBoolean();
public SafeThread(Runnable doRun) {
super(doRun);
}
// ... other constructors...
@Override
public final void run() {
if (Thread.currentThread() != this) {
throw new IllegalStateException(
thread.getState()==Thread.State.NEW ?
"use start() instead of run()" :
"run() called on started thread"
);
}
if (!run.compareAndSet(false, true)) {
throw new IllegalStateException(
"run() called recursively"
);
}
super.run();
}
}
(Disclaimer: Not compiled or tested.)
Tom Hawtin