Uploaded image for project: 'Commons Lang'
  1. Commons Lang
  2. LANG-678

Add support for ConcurrentMap.putIfAbsent()

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • None
    • 3.0
    • lang.concurrent.*
    • None

    Description

      The ConcurrentMap interface provides the putIfAbsent() method for adding keys which are not yet present in the map in an atomic operation. However, using this method is not always convenient because in many cases the return value is not what you want: If the value is newly added, null is returned. Typically the calling code is rather interested in the value which is now stored in the map. This is a proposal to add a new putIfAbsent() method to ConcurrentUtils which returns this value.

      Also, when working with a concurrent map, a typical pattern is to check whether the map contains a key. If not, a value is created and put into the map - unless another thread was faster. An example of such a use case is a map acting as a cache. ConcurrentUtils can provide support for such use cases by combining the putIfAbsent() operation with a ConcurrentInitializer: If the key is not found in the map, the initializer is called to create the corresponding value. Finally, putIfAbsent() is called to add the value to the map.

      Attachments

        1. putIfAbsent.patch
          11 kB
          Oliver Heger

        Activity

          People

            Unassigned Unassigned
            oheger Oliver Heger
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: