tags:

views:

58

answers:

3

I'm from a WinAPI / C++ background, and I'm curious as to what the Java world uses in place of a threaded message loop in a worker thread to handle communications and interactions between threads. The idea is to use a message pump in both the worker thread, and the main thread, and have them posting messages back and forth. This solution is very WinAPI / C++ centric, and probably not the preferred method of achieving this goal in Java.

What is the 'Java' way to do something like this?

+1  A: 

Sounds like a Producer-Consumer pattern.

Roman
+2  A: 

Take a look at the java.util.concurrent package here for useful concurrency related classes. BlockingQueue is probably of most interest to you in this situation.

Each thread can have a BlockingQueue to act as its message queue in a thread safe way.

ChrisH
+1 And my answer was half written when I was getting the link for the concurrent package.
Robin
A: 

In Java, the preferred way is to simply access fields from one thread another, with proper synchronization.

Synchronization is very important because it's the only way to guarantee that the value written by one thread will be seen by the others (as specified in the Java Memory Model). It can be achieved by using the synchronized keyword on methods that access the shared field (coarse-gained locks, ex: public synchronized void getMyField() ), or by locking explicitely on some finer-gained locks - which can be either the locks every object have internally (ex: synchronized(myObject)), or specialized locks provided by the java.util.concurrent package (ReadWriteLock, etc.).

For inter-thread coordination, use the Barriers, Queues and all the nice constructs also available in the java.util.concurrent package.

If you want to know more about all this, I suggest you read this book : http://www.javaconcurrencyinpractice.com/

Olivier Croisier