Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Java FAQ: Top Questions

30. What is the difference between ReentrantLock and synchronized?

ReentrantLock and synchronized are Java mechanisms for thread synchronization, but ReentrantLock offers more flexibility and features.

  • synchronized:
    • Built-in keyword for methods or blocks.
    • Automatically releases the lock on block exit.
    • Limited control (e.g., no timeout, no fairness).
  • ReentrantLock:
    • Class in java.util.concurrent.locks .
    • Explicit lock/unlock with lock() and unlock() .
    • Features: try-lock, timeouts, fairness, and condition variables.
    • Requires manual unlocking, typically in try-finally .