Devanshu Verma’s Post

🚀 30 Days of Java Interview Questions – Day 25 💡 Question: What is the difference between synchronized and Lock in java? 🔹 synchronized (Keyword) synchronized is a keyword used for thread synchronization. It locks a method or block so that only one thread can access it at a time. Example: ```java id="k2m9sa" synchronized void print() { System.out.println("Thread-safe method"); } ``` --- 🔹 Lock (Interface) Lock is part of java.util.concurrent package and provides more flexible control than synchronized. Example: ```java id="a8d2kq" Lock lock = new ReentrantLock(); lock.lock(); try { System.out.println("Thread-safe block"); } finally { lock.unlock(); } ``` 🔹 Key Differences synchronized • Simpler to use • Automatically releases lock • Less flexible Lock • More control (tryLock, fairness) • Must manually release lock • Better for complex scenarios ⚡ When to use what? Use synchronized • When simplicity is enough • Basic thread safety Use Lock • When you need advanced features • TryLock, timeout, fairness 📌 Interview Tip Lock provides better scalability and flexibility, but synchronized is easier and less error-prone. Follow this series for 30 Days of Java Interview Questions. #java #javadeveloper #codinginterview #backenddeveloper #softwareengineer #programming #developers #tech

  • text

To view or add a comment, sign in

Explore content categories