I am writing a bot in Java for a game. One thread manages time for the Manager and Worker threads and sends heartbeats for them. Manager collects and interprets messages from the server, and the Worker threads receive commands from the Manager (with detailed information in classes) and acts on this information.
Right now, I'm having trouble with multithreading deadlocks and I'm not sure if there is an alternative.
Here are some methods in my manager class: I call getMessageFromUsername from the GUI thread when the user clicks a button. The following method is called from another thread.
private ArrayList<Message> MessageList = new ArrayList<>();
public synchronized Message getMessageFromUsername(String username) {
for( Message msg : MessageList ) {
if( msg.username.equalsIgnoreCase(username) ) {
Message m = new Message(msg.num, msg.username, msg.id);
return m;
}
}
return null;
}
My manager thread reads information from the socket and adds information to MessageList in a continuous loop. (Another one, i.e.)
private synchronized void parseMessage() {}
private void main() { while(1) { parseMessage(/*Adds message to MessageList*/); Sleep(); } }
Now, my problem is a pretty noobie issue- because if I want to write to MessageList I have to use synchronized to access it. However, since this happens in a loop and the messages are constantly coming in through the socket it causes a deadlock because it keeps locking my object and this occurs in a loop.
What can I do to solve my problem with deadlocking?