Silviu
Silviu

Reputation: 65

Java: What object is more appropriate?

I am writing an application similar to a chat server-client pair.

I am planning on having a central Object which will hold new messages received from clients until they are dealt with by the main thread.

My application is multi-threaded. Each client will be on its own thread, so multiple threads will be adding messages to this central Object.

The main thread will check this Object for messages, remove the "oldest" and deal with it appropriately. Preferably I would like the messages to be handled in the same order they were added (FIFO).

What type of Object is most appropriate to hold the new messages? I looked into Vectors and ArrayLists, but I am confused about the synchronization aspect. I never worked with synchronization or threads before.

Thank you

Upvotes: 2

Views: 189

Answers (4)

whaley
whaley

Reputation: 16265

While not a direct answer (As @Alison provided a decent enough of one provided you don't need to persist messages) always have a look at the java.util.concurrent package whenever you need data structure classes or utility classes to help with multi-threaded coded: http://download-llnw.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html

Upvotes: 1

Gopi
Gopi

Reputation: 10293

You may also consider jgroups for this project.

JGroups is an open source reliable group communication toolkit. Its reliable and simple to use. Here is a basic chat example in the tutorial of same.

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328724

If this is to become more than a little toy project, you should look into JMS which solves all of the little problems that you're not aware of, yet.

A good implementation of JMS is Apache ActiveMQ (not related to IBM's MQSeries).

Upvotes: 3

Armand
Armand

Reputation: 24383

ConcurrentLinkedQueue sounds likely.

More info here: How to use ConcurrentLinkedQueue?

Javadoc here: http://download-llnw.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html

Upvotes: 5

Related Questions