3 Replies Latest reply on Aug 8, 2012 12:22 PM by EJP

    synchronized on a final map.

      Hi folks,

      I know most people like to use a dummy Object on the synchronized statement because it is static, but I wonder if I can use a final Map instead? Don't get me wrong, I am not saying I will do that. I feel it is wrong when I saw someone wrote this code. I just need a second opinion. To me, even the map is final, but it will change over time when the map get added or removed item. It is not static. Not sure it is good to be used in the synchronized statement. Any inputs will help, thanks!

      private static final Map<String, Long> MAP = new HashMap<String, Long>(100);

      public static Long getTimestamp(String id) {
      Long tiimestamp = null;
      synchronized(MAP) {
      Long t = MAP.get(id);
      if (t == null) {
      timestamp = System.currentTimeMillis();
      MAP.put(id, timestamp);
      return timestamp;

      public static String releaseLock(String id) {
      synchronized(MAP) {
      if (MAP.containsKey(id)) {
        • 1. Re: synchronized on a final map.
          Seems perfectly reasonable to me.

          First of all you don't synchronize on variables, you synchronize on objects. And since "final" refers to the variable, that means that "final" doesn't apply to your question.

          And second, it doesn't matter whether the object you choose for your synchronization monitor is mutable or not. All that matters is that all code in the critical sections (the ones which should only be run by one thread at a time) are protected by the same monitor.

          And in this case, since the critical sections are all for the purpose of modifying the map, it makes perfect sense to use the map itself as the monitor. You could certainly use some other object as the monitor, i.e. the "dummy Object" you referred to, but then the coder has to remember to use the same dummy object to protect every critical section. That's an extra thing to keep track of and potentially get wrong.
          • 2. Re: synchronized on a final map.
            Hi DrClap,

            marking as final it will be an varible.
            Can you explain in detail.
            • 3. Re: synchronized on a final map.
              marking as final it will be a variable.
              Can you explain in detail.
              Explain what in detail? Seems to me the answer was very detailed already.