Reputation: 75
I run a java server to support an android game i am working on. The server receives a client socket, opens a new thread, read the object being sent from the client and perform operations on a linkedlist.
The operations consists of, adding the new object to the linked list if the list is empty. If the list is not empty, the thread adds the object to the list and returns a different object in the list.
if (!check.getName().equals(fighter1.getName())) {
fighter2 = check;
itr.remove();
OutputStream os = clientSocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(fighter2);
oos.flush();
checkName = false;
}
This is the remove part of the thread, the adding part comes a little bit before and is basically just list.add(object);
Now, the problem is since this server can run multiple threads, what happens if 10 users connect at the same time, wouldn't this have a big chance of causing the list to have null pointers/other errors.
I want to expand this server to have the ability to handle hundreds of connection of the same time, and I'm currently just testing it with a handful of alpha testers. Got any good ideas as for how I can make the altering of data as safe as possible?
Upvotes: 2
Views: 156
Reputation: 1427
I think you should simply use a thread safe List, like CopyOnWriteArrayList, as long as speed doesn't start to matter. (Its a dirty but simple way ;) )
Upvotes: 1
Reputation: 22710
Linked list is not thread safe, you can try other thread safe collection like ConcurrentLinkedQueue
Upvotes: 0