🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)
🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)

🔧 Programmierung 🕛 kürzlich 6 Min Lesezeit
0

Part 5 - synchronized Keyword: Methods, Blocks, Thread Safety

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

In the previous article, we explored the native keyword and learned how Java communicates with C/C++ libraries using JNI.



In this article, we'll learn about one of the most important concepts in multithreaded programming:




synchronized




When multiple threads access the same object simultaneously, unexpected results can occur.



For example:




  • Two users withdraw money from the same bank account at the same time.

  • Multiple employees update the same inventory record.

  • Several threads modify a shared counter.



Without proper synchronization, data can become inconsistent.



The synchronized keyword helps solve this problem by ensuring that only one thread can execute a critical section of code at a time.



By the end of this article, you'll understand:




  • What synchronized is

  • Why thread synchronization is needed

  • Synchronized methods

  • Synchronized blocks

  • Object locks

  • Illegal modifier combinations

  • Advantages and disadvantages

  • Common interview questions









What is the synchronized Keyword?



The synchronized keyword is used to control access to shared resources in a multithreaded environment.



If a method or block is declared as synchronized, only one thread at a time can execute that code for a given object.



It is applicable to:




  • Methods

  • Blocks



It is not applicable to:




  • Classes

  • Variables

  • Constructors
































Applicable To Allowed?
Method
Block
Class
Variable
Constructor








Why Do We Need Synchronization?



Imagine a bank account with a balance of ₹10,000.



Two threads attempt to withdraw ₹7,000 simultaneously.



Without synchronization:




CODE
Balance = ₹10,000


├───────────────┐
▼ ▼
Thread A Thread B
Withdraw ₹7,000 Withdraw ₹7,000
│ │
▼ ▼
Both read ₹10,000 before either updates it


Final Balance = Incorrect






Both threads may think enough money exists and complete the withdrawal, leading to inconsistent data.









How synchronized Solves the Problem



With synchronization:




CODE
Thread A

Gets Object Lock

Executes Method

Releases Lock

───────────────►
Thread B Gets Lock






Only one thread can execute the synchronized code at a time.









Syntax






Synchronized Method






CODE
public synchronized void withdraw(double amount) {

}












Synchronized Block






CODE
synchronized (this) {

// Critical section

}












How a Synchronized Method Works



Consider this example:




CODE
class BankAccount {

private double balance = 10000;

public synchronized void withdraw(double amount) {

balance -= amount;

System.out.println("Remaining Balance: " + balance);

}

}









Step-by-Step Explanation



Step 1



A thread calls the withdraw() method.



Step 2



The JVM checks whether another thread already owns the object's lock.



Step 3



If the lock is available, the thread acquires it.



Step 4



The method executes.



Step 5



The lock is released after the method completes.









What Is an Object Lock?



Every Java object has an associated monitor (lock).



When a synchronized instance method is called:




  • The thread acquires the object's lock.

  • Other threads attempting to execute synchronized methods on the same object must wait.




CODE
BankAccount Object


Object Lock


Thread 1 ✅ Running
Thread 2 ⏳ Waiting
Thread 3 ⏳ Waiting












Synchronized Methods



Example:




CODE
class Counter {

private int count = 0;

public synchronized void increment() {

count++;

System.out.println(count);

}

}






Only one thread can execute increment() on the same Counter object at a time.









Synchronized Blocks



Sometimes only a small portion of a method needs synchronization.



Instead of synchronizing the entire method, synchronize only the critical section.



Example:




CODE
class Inventory {

private int stock = 100;

public void purchase(int quantity) {

System.out.println("Validating request...");

synchronized (this) {

stock -= quantity;

}

System.out.println("Purchase completed.");

}

}









Why Use a Synchronized Block?



Only the code that modifies shared data is synchronized.



This reduces waiting time and improves performance.









Method vs Block Synchronization
























Synchronized Method Synchronized Block
Entire method is locked Only selected code is locked
Easier to write More flexible
Can reduce performance Better performance for large methods








Illegal Combination: abstract synchronized



An abstract method has no implementation.



Example:




CODE
abstract void process();






A synchronized method requires executable code because it acquires and releases locks.



These two concepts conflict.



Incorrect:




CODE
public abstract synchronized void process();









Compile-Time Error






CODE
illegal combination of modifiers:
abstract and synchronized









Why?



An abstract method has no body.



Without a body, there is nothing to synchronize.









Advantages of synchronized






1. Prevents Data Inconsistency



Only one thread modifies shared data at a time.









2. Simplifies Thread Safety



The JVM manages locking automatically.









3. Easy to Understand



Using the synchronized keyword is straightforward compared to manual lock management.









Disadvantages of synchronized






1. Reduced Performance



Threads waiting for a lock cannot continue execution.









2. Increased Waiting Time



High contention can cause many threads to remain blocked.









3. Scalability Issues



Excessive synchronization may reduce throughput in highly concurrent applications.









Common Beginner Mistakes






Mistake 1: Synchronizing Everything



Incorrect approach:




CODE
public synchronized void processLargeFile() {

// Hundreds of lines of code

}






Prefer synchronizing only the critical section whenever possible.









Mistake 2: Assuming Synchronized Makes Code Faster



Synchronization improves correctness, not speed.









Mistake 3: Thinking Every Object Shares One Lock



Each Java object has its own monitor.



Different objects can execute synchronized methods simultaneously.









Mistake 4: Forgetting That Static Methods Use a Different Lock



A synchronized instance method locks the current object (this).



A synchronized static method locks the Class object.



This distinction is a common interview topic.









Best Practices




  • Synchronize only code that accesses shared mutable data.

  • Prefer synchronized blocks over synchronized methods when only a small section needs protection.

  • Keep synchronized sections short.

  • Avoid unnecessary synchronization in single-threaded applications.

  • Consider higher-level concurrency utilities (java.util.concurrent) for complex concurrent programming.









Interview Questions






1. What is the purpose of the synchronized keyword?



It ensures that only one thread at a time executes a synchronized method or block for a given lock.



Why interviewers ask



To evaluate your understanding of thread safety.









2. Where can synchronized be applied?




  • Methods

  • Blocks









3. Can constructors be synchronized?



No.



Constructors cannot be declared synchronized.









4. What is synchronized on an instance method?



The current object (this) is locked.









5. What is synchronized on a static method?



The Class object is locked.









6. Why is abstract synchronized illegal?



Because an abstract method has no implementation, while synchronization requires executable code.









7. Which is better: synchronized method or synchronized block?



Generally, synchronized blocks provide better flexibility and can improve performance by locking only the required code.









Quick Memory Trick 🧠



Remember LOCK:




CODE
L → Lock Object

O → One Thread

C → Critical Section

K → Keep Data Consistent






Whenever you see synchronized, think LOCK.









Key Takeaways





  • synchronized is applicable only to methods and blocks.

  • It prevents multiple threads from executing critical sections simultaneously.

  • Every Java object has its own monitor (lock).

  • Synchronized methods lock the entire method.

  • Synchronized blocks lock only selected code.


  • abstract synchronized is an illegal modifier combination.

  • Synchronization improves thread safety but may reduce performance.

  • Use synchronization only when shared mutable data is involved.






If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.



Happy Coding!

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
3 Quellen
GPT-6 Astra Release Today? OpenAI’s Next Major AI Model Is Almost Here
1 Quelle
Apple accuses OpenAI of destroying evidence as trade-secrets fight intensifies
1 Quelle
Major AI platforms go down in unprecedented simultaneous outage
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Part 5 - synchronized Keyword: Methods, Blocks, Thread Safety

Thematisch verwandte Begriffe: Part, synchronized, Keyword, Methods · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...