🔁 volatile
— Visibility in Concurrency
Purpose: Ensures that changes to a variable are always visible to all threads.
Without volatile
:
- Threads may cache variables locally → one thread’s change isn’t seen by others.
With volatile
:
- The variable is always read from and written to main memory.
- Prevents stale reads but doesn’t guarantee atomicity.
volatile boolean running = true;
public void stop() {
running = false;
}
public void run() {
while (running) {
// do something
}
}
⚠️ Use volatile
only when:
- One thread writes, others read
- No compound actions (like ++ or check-then-act)
🔒 synchronized
— Mutual Exclusion
Purpose: Guarantees exclusive access to a block/method by acquiring a lock on an object.
- Ensures only one thread executes that code at a time.
- Also provides visibility (happens-before relationships).
public synchronized void increment() {
count++;
}
// OR
public void increment() {
synchronized(this) {
count++;
}
}
🔐 synchronized static
→ locks on MyClass.class
🔐 synchronized
method/block → locks on the instance (this
or given object)
🧳 transient — Skip During Serialization
Purpose: Marks a field to be excluded from serialization (e.g., when saving to a file or sending over a network).
class User implements Serializable {
String name;
transient String password;
}
When serialized, password
will not be included.
Useful for sensitive info, or fields you don’t want/need to persist.
🌐 native
— Bridge to Non-Java Code (JNI)
Purpose: Declares that a method is implemented in native code (like C or C++) using the Java Native Interface (JNI).
public native void doSomethingNative();
Used in:
- System-level libraries (like file systems, device drivers)
- Performance-critical operations
❗ No method body in Java — implementation is provided in a .dll
or .so
library, loaded via System.loadLibrary()
.
🧠 Summary Table
Keyword | Category | Purpose |
---|---|---|
volatile | Concurrency | Ensures visibility of variable changes across threads |
synchronized | Concurrency | Provides mutual exclusion and memory visibility |
transient | Serialization | Excludes field from serialization |
native | JNI (Interop) | Indicates method is implemented in native code (C/C++) |