Pergunta

We had come across an issue in our code, due to a bean which was implemented as a singleton but was not stateless. Due to which, when there are multiple requests (web service) triggered at the same time, there are exceptions and does not return the proper response.

Could this have been caught using Junit? If so, how do we use Junit for the same? If not, are there any other alternatives?

Foi útil?

Solução

Once the problem is suspected junit can be used to prove the problem is real but it is not suited for enforcing the best practice being violated here.

"Singletons shouldn't have state."

That's a sentence more at home in a coding standards document and perhaps enforced with a static code analysis tool.

Trying to prove that something DOESN'T have any concurrency issues by throwing threads at it is next to impossible. If you do, and you get lucky, you might prove it does have problems. You'll never prove it doesn't.

Much better to know and follow best practices and get some one else to look over your code.

Actually I'm not 100% sure singletons should never have state. But when they do they'd better be synchronized or immutable if they are being shared across threads.

Outras dicas

You can use threads with JUnit, just fire up a couple of background threads to invoke the service concurrently, and then invoke the service on the main thread and see if the test passes or not. Personally, I've used this approach to test e.g. (optimistic/pessimistic) locking. However, I'd say this is not a particularly reliable method in pinpointing most concurrency issues.

A better alternative is to use a load testing tool, such as SoapUI or JMeter, and invoke the web service with multiple concurrent consumers, preferably for longer period of time, and see if this generates errors.

In either case, you have to plan for these types of test, i.e.anticipate concurrency problems.

Edit: code review (by people with good experience in concurrency) is also a very effective means of catching concurrency issues. Static code analysis may also help in particular cases, but I would not bet on it alone.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top