Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The easiest way to perform asynchronous operations in Java web applications

I have Java servlet-based web applications. I would like to implement some operations in asynchronous manner, like for example writing to a log.

I would like to avoid JMS overhead and do something simple.

Managing threads myself doesn’t seem such a good idea in a server environment, you would probably need to tap into server thread pool etc. What is the best alternative for simple asynchronous operation?

Edit:

Just for clarification, since many suggested using log4j or other logging library, writing to a log operation is here more of an example. I am interested how to perform asynchronously any operation that need not be performed sequentially. Idea is to reply to user immediately and to continue processing costly operation in another thread.

In regards to log issue, we have an audit log we implemented to write a lot of data to a database and is used by the user during audit operations and at Help Desk. Writing a lot of information to DB can be very costly. We do use log4j for system log and since the appender is file appender we have no performance issues with our system log.

like image 203
Dan Avatar asked Nov 14 '22 14:11

Dan


1 Answers

As many people said here, logging is not a good candidate for async. Nevertheless, I consider you have a good reason to belive otherwise.

In such a case, I'd use a Queue (e.g. ConcurrentLinkedQueue), and a low-priority thread (which you start at application startup and kill on shutdown, for instance, from a run-at-startup servlet). The thread should pick the messages from the Queue, and do it's deed. Thread should be woken up by a notify() method or in equal intervals.

Risk: Queue can grow uncontrollably under heavy load (as the thread may not get enough CPU cycles).

There are other ways to fire an async operation (e.g. Timer, Future, ...) but I don't think they are a good fit for fast small operations.

like image 50
Vladimir Dyuzhev Avatar answered Dec 23 '22 11:12

Vladimir Dyuzhev