Re: data shared between threads and synchronized on different
objects
On Tue, 2 Aug 2011, Marcin Rodzik wrote:
I have a thread (the essential piece of its code can be found here:
http://pastebin.com/KM8Yiqgs) which sends some objects ("tasks") over
the network (in method tryToSendTask). Another thread submits objects
to be sent by means of the first thread's method submit - namely, the
"task" is put into queue.
[...]
What do you think?
I think you can make this a good bit simpler by using a BlockingQueue,
such as a LinkedBlockingQueue. Any concurrency advantage a
ConcurrentLinkedQueue might have is lost by the use of a synchronized
method in your object.
With a BlockingQueue, the code looks more like:
public void submit(T t) {
t.put(t);
}
public void run() {
long timeout = Long.MAX_VALUE;
while (goOn) {
T t = taskSendingQueue.poll(timeout, TimeUnit.SECONDS);
if (t != null) {
sendTask(t);
timeout = 0;
}
else {
taskOutputStream.flush();
timeout = Long.MAX_VALUE;
}
}
completeCommunication();
}
I am mildly abusing poll here, by using extreme values of the timeout to
effectively switch between blocking and non-blocking modes.
I don't know what this waitableClosing thing is, but i suspect you should
combine it with goOn. A loop doesn't need more than one condition
variable.
tom
--
a blood-spattered Canadarm flinging goat carcasses into the void