0

I've been trying to understand how to implement a client-server system for a multiplayer game in Java. I'm now at the "Reconciliation" part, and thought using a ConcurrentSkipListMap might be the best data structure, but I've never messed with it.

I'm struggling to understand how to efficiently play with that class: what are the Big-Os of operations, which ones are effectively fastest or more secure for thread-access, etc.

For example, here is an excerpt:

public class StateRecords {

    /**
     * The {@link Long} is the Timestamp of the server's generated GameStateDto (Objects here, for simplicity's sake).
     */
    private ConcurrentNavigableMap<Long, Object> localRecord = new ConcurrentSkipListMap<>();

    public StateRecords() {
    }

    public void discardUpTo(Long timestamp) {
        /* 1) One possible way to do it. */
        Long lowerKey = localRecord.lowerKey(timestamp);
        while(lowerKey != null) {
            localRecord.remove(lowerKey);
            lowerKey = localRecord.lowerKey(timestamp);
        }

        /* 2) Another possible way to do it. */
        localRecord.headMap(timestamp).forEach((k,v) -> localRecord.remove(k));

        /* 3) Yet some other solution. */
        localRecord.headMap(timestamp).clear();

        /* 4) I believe that one is wrong. */
        localRecord = localRecord.tailMap(timestamp, true);
    }
}

I was trying to figure out what would be the best way to remove all the entries with keys lower than the input of the method. Both the network thread and the ui-rendering thread of the client might access this structure at once (or at least, that's what I've figured so far).

Any insight would help.

payne
  • 4,691
  • 8
  • 37
  • 85
  • Premature optimization is the root of all evil. Just use the class as you need; Thread safety will save you more time than you'll be able to gain by figuring out what methods to call. Also, chances are that exact behavior might change between JDK/JVM updates. If you come across performance bottlenecks, identify them as they come up. – daniu Jun 17 '20 at 14:18
  • Learning to use the right method for what you need doesn't sound like premature optimisation to me. – payne Jun 17 '20 at 14:22
  • 1
    It is if you start considering what O()-complexity they have. Your loop looks fine; the `ConcurrentSkipListMap` "implements a concurrent variant of SkipLists providing expected average log(n) time cost for the containsKey, get, put and remove operations and their variants. Insertion, removal, update, and access operations safely execute concurrently by multiple threads.`, so it's thread safe. – daniu Jun 17 '20 at 14:26
  • Moreover, I might have forgotten to mention this piece of code gets called every few milliseconds by my game loop. – payne Jun 20 '20 at 17:39

0 Answers0