I've never really done anything with concurrency, so I'm not sure if this is done correctly.
Basically, I have a class that handles all messages from the server and decides what to do them. It uses a separate thread to keep looping through a list to check for any new messages it has to deal with.
The main server thread needs to be able to add messages to the ArrayList
without causing a concurrency error, and so far it seems ok but I don't have that many messages coming in.
public class MessageThread implements Runnable {
public static ArrayList<Message> messages = new ArrayList<Message>();
@Override
public void run() {
while (true) {
synchronized (messages) {
for (Message m : messages) {
}
}
}
public static void addMessage(Message message) {
synchronized (messages) {
messages.add(message);
}
}
public static void removeMessage(Message message) {
synchronized (messages) {
messages.remove(message);
}
}
}
So as you can see, the server thread would use the MessageThread.addMessage
method whenever it needs to add a message.
List<Message> messages = new ArrayList<Message>();
also have you checked out using theCollections
API?Collections.synchronizedList(messages)
. \$\endgroup\$ – Lam Chau Nov 14 '12 at 8:14