Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java methods and race condition in a jsp/servlets application

Suppose that I have a method called doSomething() and I want to use this method in a multithreaded application (each servlet inherits from HttpServlet).I'm wondering if it is possible that a race condition will occur in the following cases:

  1. doSomething() is not staic method and it writes values to a database.
  2. doSomething() is static method but it does not write values to a database.

what I have noticed that many methods in my application may lead to a race condition or dirty read/write. for example , I have a Poll System , and for each voting operation, a certain method will change a single cell value for that poll as the following:

[poll_id |              poll_data        ]
[1       | {choice_1 : 10, choice_2 : 20}]

will the JSP/Servlets app solve these issues by itself, or I have to solve all that by myself?

Thanks..

like image 666
Abdullah Avatar asked Jan 19 '26 01:01

Abdullah


2 Answers

It depends on how doSomething() is implemented and what it actually does. I assume writing to the database uses JDBC connections, which are not threadsafe. The preferred way of doing that would be to create ThreadLocal JDBC connections.

As for the second case, it depends on what is going on in the method. If it doesn't access any shared, mutable state then there isn't a problem. If it does, you probably will need to lock appropriately, which may involve adding locks to every other access to those variables.

(Be aware that just marking these methods as synchronized does not fix any concurrency bugs. If doSomething() incremented a value on a shared object, then all accesses to that variable need to be synchronized since i++ is not an atomic operation. If it is something as simple as incrementing a counter, you could use AtomicInteger.incrementAndGet().)

like image 170
Mike Avatar answered Jan 21 '26 13:01

Mike


The Servlet API certainly does not magically make concurrency a non-issue for you.

When writing to a database, it depends on the concurrency strategy in your persistence layer. Pessimistic locking, optimistic locking, last-in-wins? There's way more going on when you 'write to a database' that you need to decide how you're going to handle. What is it you want to have happen when two people click the button at the same time?

Making doSomething static doesn't seem to have too much bearing on the issue. What's happening in there is the relevant part. Is it modifying static variables? Then yes, there could be race conditions.

like image 45
Affe Avatar answered Jan 21 '26 13:01

Affe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!