Java: synchronized put() with a list of objects

I'm using a LinkedBlockingQueue to handle message objects from other threads. For example, I have something like this: LinkedBlockingQueue message_queue = new LinkedBlockingQueue(); public void run(){ while(true){ Message m = message_queue.take(); handle_message(m); } } When I add a new message from another thread, I call message_queue.put(m). No problem! My question is this: How do I synchronize the addition of a SET of messages all at once? Let's say I want to do this: Message[] messages = {/* some list of message objects */}; for (Message m : messages){ message_queue.put(m); } The problem is that another thread could be doing the same thing, and the messages from one thread are not guaranteed to be queued exactly as I intend. Messages from the competing thread can be "interleaved" inbetween (i.e. the actual sequence could end up being A, A, B, B, A, B instead of the intended A, A, A, B, B, B) I know I could put the loop in the "put" example into a "synchronized(message_queue){}" block, but would I also need to put that same block around the call to .take()? And obviously, I can't do that, as it would instantly create a deadlock situation, since take() blocks until a new Message is put(), which cannot happen when locked by synchronization. Can I skip the synchronized block on the take() call, having only a synchronized block on the put loop, and get the desired effect? Thanks!

以上就是Java: synchronized put() with a list of objects的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏