views:

80

answers:

4

I need to maintain a list of userids (proxy accounts) which will be dished out to multithreaded clients. Basically the clients will use the userids to perform actions; but for this question, it is not important what these actions are. When a client gets hold of a userid, it is not available to other clients until the action is completed.

I'm trying to think of a concurrent data structure to maintain this pool of userids. Any ideas ? Would a ConcurrentQueue do the job ? Clients will dequeue a userid, and add back the userid when they are finished with it.

A: 

Do you really need to have a limited pool of userids ? Otherwise, each user can simply have an incrementing userid. This way, there's no risk of collision, and it seems much easier to me.

Valentin Rocher
Even if the user ids need to not be reused, most probably id collisions would not be acceptable.
cherouvim
The set of available userids are specifically managed by a separate 3rd party system. I have no choice.
Jacques René Mesrine
A: 

I would use a BlockinQueue.

This would enable client threads to poll ids (until there is one available or time limit is exceeded) and push them back after use.

mkorpela
+2  A: 

For a similar situation I implemented my own BlockingQueue. As long as you keep track of the pool of ids you can shutdown the queue at an appropriate time.

Lars Andren
A: 

Is a BlockingQueue appropriate? What action should be taken if the Queue is empty? It sounds like you probably have a limited number of connections to your third party software. In that case, you might want to display an explanatory message to any user who cannot obtain a user ID. In that case, blocking wouldn't be useful. You could just implement some synchronization around a standard Queue and handle empty Queues as you see fit. Something like this?

public class UserIDQueue {
private static final Queue<String> USER_IDS = loadUserIDs();
private static final Object USER_ID_LOCK = new Object();

//doesn't need to be synchronized as it is called at class load time
private static Queue<String> loadUserIDs() {
    Queue<String> userIDs = new LinkedList<String>();
    for(String userID : THIRD_PARTY_USER_IDS) {
        userIDs.add(userID);
    }
    return userIDs;
}

public static String getNextUserID() {
    synchronized(USER_ID_LOCK) {
        String userID = USER_IDS.poll();
        if (userID == null) {
            //not sure what your logic is, probably an exception
        }
        return userID;
    }
}

public static void returnUserID(String userID) {
    synchronized(USER_ID_LOCK) {
        USER_IDS.add(userID);
    }
}

}

John D