简体   繁体   中英

Java multithreading and linkedlist operations

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?

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

链接列表不是线程安全的,您可以尝试其他线程安全的集合,例如ConcurrentLinkedQueue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM