Reputation: 959
I have a static Vector users, each user has one or more accounts, so for every User there is a Vector accounts. Users and Accounts has an unique id. Adding a new User is simple: i got a static Vector and i can easily check the id of the last User and i can get the new id for the new User doing user.getId()+1.
After a new User is added a problem comes by adding a new Account. An Account id must be unique, so i have to check for the largest id contained in every user's Accounts Vector. Provided that many processes can add/remove users and Accounts, what is the best way to synchronize all the Account vectors and safely add/remove accounts?
Actually, a User is added as follows
public boolean addNewUser(User user)
{
if(user!=null)
{
int id=getNewUserId();
if(id!=-1)
{
user.setId(id);
utenti.add(user);
return false;
}
else
return false;
}
else
return false;
}
private int getNewUserId()
{
User user=utenti.lastElement();
if(user!=null)
return user.getId()+1;
else
return -1;
}
Upvotes: 2
Views: 57
Reputation: 1645
Probably not the most efficient way, but you could make an int and then go through the sizes of every list of accounts for every user.
int id = 0;
for (User user : AllUsers) {
id += user.listOfAccounts.size();
}
Now your id will be the last id. Simply add 1 when you create a new account.
Note that there will be problems if it's possible to delete accounts.
Upvotes: 1
Reputation: 810
Concerning the id, I recommend using a long value that you increment all the time (regadless of accounts being deleted).
Synchronizing will be harder and depends on what you want to do. An easy rule would be, if you have a list object, use a synchronized block whenever you access it (read or write):
synchronized(myList) {
//update the list, do whatever you like, there is no concurrent modification
}
Depending on your exact usage, there might be better ways, but this should work.
Upvotes: 1