1

Could you advise me how to implements queue in multithreaded application.

I have to register events in my application in queue (events from all users) which I flush and save to database every 100 events to improve performance. I don't want save database log for every single user commit. I suppose commit e.x. every 100 events to database will be faster that 100 single commits. I have three ideas:

  • use ThreadLocal
  • use queue for single user
  • use synchronized LinkedList and flush from time to time or every number of events

Do you have any other ideas? I don't use log4j because I have to save log to database - not to file, which method will the best?

Przemek Nowak
  • 7,173
  • 3
  • 53
  • 57
  • No need to implement it yourself: http://stackoverflow.com/questions/1364322/log-to-a-database-using-log4j – meriton Oct 14 '10 at 18:24

1 Answers1

2

You could try a BlockingQueue implementation like ArrayBlockingQueue. Any thread can safely add an event to the queue, and one (or more) threads can safely remove elements from the queue. Have a background thread wait for events on the queue (BlockingQueue.take()). Once you collect 100 elements, do your stuff.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190