Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

76
LINES

< > BotCompany Repo | #1012172 // Bench concurrency-safely iterating TreeMap faster with interference [OK]

JavaX source code (desktop) [tags: use-pretranspiled] - run with: x30.jar

Download Jar. Libraryless. Click here for Pure Java version (1734L/11K).

!7

static int n = 1000000;
sbool done;

// iterate safely (& quickly) in the face of concurrent modifications
// is now called concurrentlyIterateKeys in the library
static <A, B> IterableIterator<A> iterateKeysQuickly(final NavigableMap<A, B> map) {
  ret iteratorFromFunction(new F0<A>() {
    Iterator<A> it = keys(map).iterator();
    A key;
    
    A get() {
      synchronized(map) {
        try {
          if (!it.hasNext()) null;
          ret key = it.next();
        } catch (ConcurrentModificationException e) {
          print("Re-iterating");
          it = map.tailMap(key, false).keySet().iterator();
          if (!it.hasNext()) null;
          ret key = it.next(); // Can't throw another exception
        }
      }
    }
  });
}

p {
  final NavigableMap<S, Bool> map = synchroNavigableMap(litcimap());
  final new L<S> ids;
  repeat n {
    map.put(addAndReturn(ids, randomID()), Bool.TRUE);
  }
  
  long sum = 0;
  repeat 5 {
    int i = 0;
    sum = 0;
    time "Iterating" {
      for (S key : keys(map)) {
        if (!key.startsWith("_")) {
          ++i;
          sum += key.hashCode();
        }
      }
    }
    assertEquals(i, n);
  }

  thread "Interfere" {
    repeat with ms sleep 10 {
      if (done) ret;
      synchronized(map) {
        map.put("_" + randomID(), Bool.TRUE);
      }
    }
  }
  
  repeat 5 {
    int i = 0;
    long sum2 = 0;
    time "Iterating quickly" {
      for (S key : iterateKeysQuickly(map)) {
        if (!key.startsWith("_")) {
          ++i;
          sum2 += key.hashCode();
        }
      }
    }
    assertEquals(i, n);
    assertEquals(sum, sum2);
  }
  
  done = true;
}

Author comment

Began life as a copy of #1012169

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1012172
Snippet name: Bench concurrency-safely iterating TreeMap faster with interference [OK]
Eternal ID of this version: #1012172/7
Text MD5: 5b386502410a4e4dc306af43383e7097
Transpilation MD5: 744845ef2b81cc992f6ea18302c24cbd
Author: stefan
Category: javax / collections
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2017-11-23 11:21:40
Source code size: 1721 bytes / 76 lines
Pitched / IR pitched: No / No
Views / Downloads: 400 / 864
Version history: 6 change(s)
Referenced in: [show references]