Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7900333
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T08:56:40+00:00 2026-06-03T08:56:40+00:00

Is this class thread-safe? class Counter { private ConcurrentMap<String, AtomicLong> map = new ConcurrentHashMap<String,

  • 0

Is this class thread-safe?

class Counter {
  private ConcurrentMap<String, AtomicLong> map = 
    new ConcurrentHashMap<String, AtomicLong>();
  public long add(String name) {
    if (this.map.get(name) == null) {
      this.map.putIfAbsent(name, new AtomicLong());
    }
    return this.map.get(name).incrementAndGet();
  }
}

What do you think?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T08:56:42+00:00Added an answer on June 3, 2026 at 8:56 am

    Yes, provided you make the map final. The if is not necessary but you can keep it for performance reasons if you want, although it will most likely not make a noticeable difference:

    public long add(String name) {
      this.map.putIfAbsent(name, new AtomicLong());
      return this.map.get(name).incrementAndGet();
    }
    

    EDIT

    For the sake of it, I have quickly tested both implementation (with and without the check). 10 millions calls on the same string take:

    • 250 ms with the check
    • 480 ms without the check

    Which confirms what I said: unless you call this method millions of time or it is in performance critical part of your code, it does not make a difference.

    EDIT 2

    Full test result – see the BetterCounter which yields even better results. Now the test is very specific (no contention + the get always works) and does not necessarily correspond to your usage.

    Counter: 482 ms
    LazyCounter: 207 ms
    MPCounter: 303 ms
    BetterCounter: 135 ms

    public class Test {
    
        public static void main(String args[]) throws IOException {
            Counter count = new Counter();
            LazyCounter lazyCount = new LazyCounter();
            MPCounter mpCount = new MPCounter();
            BetterCounter betterCount = new BetterCounter();
    
            //WARM UP
            for (int i = 0; i < 10_000_000; i++) {
                count.add("abc");
                lazyCount.add("abc");
                mpCount.add("abc");
                betterCount.add("abc");
            }
    
            //TEST
            long start = System.nanoTime();
            for (int i = 0; i < 10_000_000; i++) {
                count.add("abc");
            }
            long end = System.nanoTime();
            System.out.println((end - start) / 1000000);
    
            start = System.nanoTime();
            for (int i = 0; i < 10_000_000; i++) {
                lazyCount.add("abc");
            }
            end = System.nanoTime();
            System.out.println((end - start) / 1000000);
    
            start = System.nanoTime();
            for (int i = 0; i < 10_000_000; i++) {
                mpCount.add("abc");
            }
            end = System.nanoTime();
            System.out.println((end - start) / 1000000);
    
            start = System.nanoTime();
            for (int i = 0; i < 10_000_000; i++) {
                betterCount.add("abc");
            }
            end = System.nanoTime();
            System.out.println((end - start) / 1000000);        
        }
    
        static class Counter {
    
            private final ConcurrentMap<String, AtomicLong> map =
                    new ConcurrentHashMap<String, AtomicLong>();
    
            public long add(String name) {
                this.map.putIfAbsent(name, new AtomicLong());
                return this.map.get(name).incrementAndGet();
            }
        }
    
        static class LazyCounter {
    
            private final ConcurrentMap<String, AtomicLong> map =
                    new ConcurrentHashMap<String, AtomicLong>();
    
            public long add(String name) {
                if (this.map.get(name) == null) {
                    this.map.putIfAbsent(name, new AtomicLong());
                }
                return this.map.get(name).incrementAndGet();
            }
        }
    
        static class BetterCounter {
    
            private final ConcurrentMap<String, AtomicLong> map =
                    new ConcurrentHashMap<String, AtomicLong>();
    
                public long add(String name) {
                    AtomicLong counter = this.map.get(name);
                    if (counter != null)
                        return counter.incrementAndGet();
    
                    AtomicLong newCounter = new AtomicLong();
                    counter = this.map.putIfAbsent(name, newCounter);
    
                    return (counter == null ? newCounter.incrementAndGet() : counter.incrementAndGet());
                }
        }
    
        static class MPCounter {
    
            private final ConcurrentMap<String, AtomicLong> map =
                    new ConcurrentHashMap<String, AtomicLong>();
    
            public long add(String name) {
                final AtomicLong newVal = new AtomicLong(),
                        prevVal = map.putIfAbsent(name, newVal);
                return (prevVal != null ? prevVal : newVal).incrementAndGet();
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is my simple program in Java: public class Counter extends Thread { public
Take this code: public class MyClass { private final Object _lock = new Object();
Why is this java class not Thread safe. class TestClass { private int x;
In C++ , during a class constructor, I started a new thread with this
Given this class public partial class Default : Page { private IRepository repo; ...
Take this class as example: public class Category : PersistentObject<int> { public virtual string
Is this class thread-safe? Is it possible to see inconsistent values? Lets say initially
I have a class like the below and am wondering, will this be thread-safe
Short Version Are class variables thread-safe for the duration of a controller action? Long
I'm having trouble adding a copy constructor to this class: http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html I need to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.