function tf = loadDistanceData(connectionName, cacheName)
% loadDistanceData Load data into the cache; sync. with a distributed lock.
% If the graph of distances has not yet been loaded into the cache,
% create it from an Excel spreadsheet and write it to the cache. Since
% this operation must be performed by only one MPS worker, use a
% synchronizing lock.

% Copyright 1984-2019 The MathWorks, Inc.
% All Rights Reserved.

    % Connect to the cache that will store the distance data
    c = mps.cache.connect(cacheName,'Connection',connectionName);
    
    % While the data has not been loaded (by us or a different worker),
    % try to acquire a lock that will allow us to safely write to the cache.
    % Limit the number of times we'll try to load the data. 
    tries = 0;
    while isKey(c,'Distances') == false && tries < 6
        % Try to acqure a lock on a mutex named 'DistanceData'.
        lk = mps.sync.mutex('DistanceData','Connection',connectionName);
        if acquire(lk,10)
            % Another worker might have loaded the data while we were
            % waiting to acquire the lock. If so, nothing else to do.
            if isKey(c,'Distances') == false
                % We have the lock, and the data doesn't exist yet, so
                % create it and store it in the cache.
                g = initDistanceData('Distances.xlsx');
                c.Distances = g;
            end
            % Release the lock.
            release(lk);
        end
        % Remember how many times we've tried.
        tries = tries + 1;
    end
    % Is the data now successfully loaded and ready for use?
    tf = isKey(c,'Distances');
end