Difference between VOLATILE | ATOMICITY | SYNCHRONISATION keywords A. Use Volatile if you only care about threads seeing the latest value of a boolean or reference. class Worker extends Thread { private volatile boolean running = true; // Visibility guaranteed public void run() { while (running) { // Some operations } } public void stopWorker() { running = false; } } B. Use Atomic variables if you are just performing math or simple updates on a single counter. import java.util.concurrent.atomic.AtomicInteger; AtomicInteger counter = new AtomicInteger(0); counter.incrementAndGet(); // Thread safe addition C. Use Synchronized if you need to perform multiple steps that must stay together as one public synchronized void transfer(Account to, int amount) { if (this.balance >= amount) { this.balance -= amount; to.deposit(amount); } #Java #BackendDevelopment #SoftwareEngineering #MultiThreading #Concurrency #JavaPerformance #CodingTips #Programming #SystemDesign }
Volatile vs Atomic vs Synchronized in Java Multithreading
More Relevant Posts
-
Dynamic binding in Java feels like magic—until you realize it’s the JVM calling the shots at runtime. This post breaks down what’s happening behind the curtain when method calls don’t match reference types. What you’ll learn: 1. How .toString() behaves across reference types 2. Why runtime picks the method, not the compiler 3. Key differences between Java and C++ binding 4. How dynamic binding powers polymorphism #JavaTips #OOP #DynamicBinding #JavaInternals #RheinwerkComputingBlog #DevSkills Master the runtime rules: https://hubs.la/Q049N3m30
To view or add a comment, sign in
-
-
Dynamic binding in Java feels like magic—until you realize it’s the JVM calling the shots at runtime. This post breaks down what’s happening behind the curtain when method calls don’t match reference types. What you’ll learn: 1. How .toString() behaves across reference types 2. Why runtime picks the method, not the compiler 3. Key differences between Java and C++ binding 4. How dynamic binding powers polymorphism #JavaTips #OOP #DynamicBinding #JavaInternals #RheinwerkComputingBlog #DevSkills Master the runtime rules: https://hubs.la/Q04byChg0
To view or add a comment, sign in
-
-
💡 𝗝𝗮𝘃𝗮/𝐒𝐩𝐫𝐢𝐧𝐠 𝐁𝐨𝐨𝐭 𝗧𝗶𝗽 - 𝗦𝘄𝗶𝘁𝗰𝗵 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 💎 🕯 𝗧𝗿𝗮𝗱𝗶𝘁𝗶𝗼𝗻𝗮𝗹 𝗦𝘄𝗶𝘁𝗰𝗵 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 The traditional switch statement has been part of Java since the beginning. It requires explicit break statements to prevent fall-through, which can lead to bugs if forgotten. Each case must contain statements that execute sequentially, making the code verbose and error-prone. 💡 𝗠𝗼𝗱𝗲𝗿𝗻 𝗦𝘄𝗶𝘁𝗰𝗵 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 Switch expressions were introduced in Java 14 as a more concise and safe alternative. Using the -> syntax, you eliminate the need for break statements and can directly return values. Multiple cases can be grouped with commas, and the compiler enforces exhaustiveness for better safety. ✅ 𝗞𝗲𝘆 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀 ◾ No break statements, safer and cleaner code. ◾ Direct value assignment, treat switch as an expression. ◾ Multiple labels with comma separation. ◾ Compiler exhaustiveness checks, fewer runtime errors. 🤔 Which one do you prefer? #java #springboot #programming #softwareengineering #softwaredevelopment
To view or add a comment, sign in
-
-
Stopping Threads Safely: Java does not allow killing a thread directly. Use interrupts as the “polite” way to request a thread to stop. Threads should check Thread.interrupted() or catch InterruptedException. Raw Threads vs Thread Pools With raw threads, you can interrupt them directly. With ThreadPool threads, you use ExecutorService.shutdown() or Future.cancel() to signal cancellation. Callable and Future: Wrapping tasks in Callable allows you to manage them with Future. Future.cancel(true) interrupts the task if it’s running. Useful for applying timeouts on long-running tasks. Volatile / AtomicBoolean Flags: Another approach is using a shared flag (volatile boolean stop = false;). The thread periodically checks this flag to decide whether to exit. AtomicBoolean provides thread-safe updates. Timeout Strategies: Use Thread.sleep() or scheduled tasks to enforce conditional timeouts. For blocking operations (DB calls, HTTP requests), combine interrupts with timeout-aware APIs. Example: future.get(timeout, TimeUnit.SECONDS). Practical Applications: Database Calls: Long stored procedures can be interrupted if they exceed SLA. HTTP Requests: Wrap in Future with timeout to avoid hanging threads. Schedulers: Cancel tasks after a fixed duration to maintain responsiveness. #Java #BackendDevelopment #SoftwareEngineering #MultiThreading #Concurrency #JavaPerformance #CodingTips #Programming #SystemDesign
To view or add a comment, sign in
-
Day 69 of #100DaysOfLeetCode 💻✅ Solved #349. Intersection of Two Arrays problem in Java. Approach: • Iterated through each element of the first array • Checked if the element exists in the second array • Used a temporary array to store intersection elements • Ensured no duplicates by checking already added elements • Copied the result into a final array of correct size Performance: ✓ Runtime: 4 ms (Beats 35.60%) ✓ Memory: 44.41 MB (Beats 96.71%) Key Learning: ✓ Practiced array traversal using nested loops ✓ Learned how to handle duplicates manually ✓ Improved understanding of set-like operations without using extra data structures Learning one problem every single day 🚀 #Java #LeetCode #DSA #Arrays #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🔢 Divisible Sum Pairs Problem | Java Solution 💻 Today I solved an interesting problem based on arrays and modular arithmetic! 📌 Problem: Given an array and a number k, count pairs (i, j) such that: 👉 i < j 👉 (arr[i] + arr[j]) % k == 0 ⚡ Approach: Instead of brute force O(n²), I used an optimized O(n) approach using remainder frequency. ✔️ Key Idea: Store frequency of (element % k) For each element, find its complement remainder Count valid pairs efficiently 💡 This improves performance significantly for large inputs! 🧠 Concepts Used: Arrays Modulo Arithmetic Hashing Technique 👨💻 Language: Java #Java #CodingPractice #DataStructures #Algorithms
To view or add a comment, sign in
-
-
Just learned something that clicked for me today! 💡 The Frequency Counting Pattern in Java — one of the most used patterns in DSA! The idea is simple: → Use HashMap to count occurrences → Key = element, Value = count → One loop. Done. O(n)! HashMap<Integer, Integer> freq = new HashMap<>(); for (int num : arr) { freq.merge(num, 1, Integer::sum); } This single pattern helped me solve: ✅ Finding duplicates ✅ Most/least frequent element ✅ Character frequency in strings ✅ Two Sum Brute force = O(n²) 😴 HashMap pattern = O(n) 🚀 Still learning and loving every bit of it! Building a Banking System to practice all concepts 🏦 #Java #DSA #LearningInPublic #100DaysOfCode #JavaDeveloper #DataStructures #Programming
To view or add a comment, sign in
-
-
Nested types are a powerful way to organize and encapsulate logic in Java — but understanding the difference between static and non‑static nested types is key to using them effectively. This post breaks down how each kind works, how they access outer class members, how instances are created, and what the compiler does behind the scenes. Whether you’re structuring helper classes or managing deeper hierarchies, mastering nested types will help you write cleaner, more maintainable Java code. #Java #Programming #SoftwareDevelopment #RheinwerkComputingBlog Read the full post: https://hubs.la/Q048Shz50
To view or add a comment, sign in
-
-
Day 68 of #100DaysOfLeetCode 💻✅ Solved #977. Squares of a Sorted Array problem in Java. Approach: • Traversed the array and squared each element • Used Arrays.sort() to sort the squared values • Returned the sorted array as the result Performance: ✓ Runtime: 10 ms (Beats 37.38% submissions) ✓ Memory: 47.98 MB (Beats 18.78% submissions) Key Learning: ✓ Practiced array transformation and sorting ✓ Learned how squaring affects order in sorted arrays ✓ Understood the importance of optimizing from O(n log n) to O(n) using two pointers Learning one problem every single day 🚀 #Java #LeetCode #DSA #Arrays #Sorting #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 23 of #75DaysOfCode Solved: Equal Row and Column Pairs 🔹 Problem: Given an n x n matrix, count the number of pairs (ri, cj) such that row ri and column cj are exactly the same. 🔹 Approach: • Stored all rows in a HashMap with their frequency • Converted each column into a comparable string format • Matched columns with stored rows to count equal pairs 🔹 Key Learning: Using StringBuilder instead of String concatenation significantly improves performance due to immutability of Strings in Java. 🔹 Time Complexity: O(n²) 🔹 Takeaway: Smart use of HashMap + efficient string handling can simplify and optimize matrix-based problems. #Day22 #75DaysOfCode #Java #DSA #LeetCode #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development