CKTIS / Java
Object — the common base class of objects
Object is the root of Java's class hierarchy. Learn the difference between a reference type and an object's class, and how getClass(), wait(), and notifyAll() work with a monitor.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
Object value = new Object();
Class<?> type = value.getClass();
synchronized (monitor) {
while (!condition) {
monitor.wait();
}
}
synchronized (monitor) {
// Update condition under the same monitor.
monitor.notifyAll();
}java.lang.Object is the root of the class hierarchy; every other class inherits from it directly or indirectly. An Object reference can refer to any object, including an array, or hold null. Primitive values are not objects.
Object.getClass() returns a Class object describing the object's runtime class, not the variable's declared type. In the example, value has type Object but refers to a String, so comparison with String.class produces true.
Object.wait() and Object.notifyAll() require ownership of that same object's monitor, usually through synchronized (monitor); otherwise they throw IllegalMonitorStateException. wait() releases that monitor while waiting and reacquires it before the call completes; it does not release other objects' monitors. It can throw InterruptedException.
Check the condition in a while loop because spurious wakeups are possible. notifyAll() wakes all threads waiting on that monitor but does not release its lock. Read and change the condition under the same monitor. The example illustrates these rules; it targets Java SE 21 and does not attest the production runtime version.
Examples
public class Main {
private static final Object monitor = new Object();
private static boolean ready;
public static void main(String[] args) throws InterruptedException {
Object value = "hello";
System.out.println(value.getClass() == String.class);
Thread worker = new Thread(() -> {
synchronized (monitor) {
ready = true;
monitor.notifyAll();
}
});
synchronized (monitor) {
worker.start();
while (!ready) {
monitor.wait();
}
System.out.println("ready");
}
worker.join();
}
}Result
true ready
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.