Tuesday, August 18, 2015

sleep() vs wait()

Thread.sleep() is used for time-synchronization.
Thread.sleep(5000); // no synchronization needed

object.wait() is used for multi-thread-synchronization.
synchronized (lock) {
  while (!condition) {
    lock.wait(); // releases lock
  }
}
synchronized (lock) {
  lock.notify();
}

When to write your own exceptions

When you need to differentiate between different types of errors.

Exception class only tells you something is wrong but not what.

Allows code to ignore certain types of errors at certain points in code and let other parts handle it.