开发者

How to maintain a pool of names?

开发者 https://www.devze.com 2022-12-28 19:53 出处:网络
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

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 idea开发者_开发技巧s ? Would a ConcurrentQueue do the job ? Clients will dequeue a userid, and add back the userid when they are finished with it.


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.


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.


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.


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);
    }
}

}

0

精彩评论

暂无评论...
验证码 换一张
取 消