This multi-threaded application access a laid upward of spider web services that update parts of a database. The work is messages arriving inwards the rabbit mq charabanc are asynchronous as well as are non actually aware of each other. So in that place powerfulness travel a fourth dimension that ii dissimilar requests that access the same utilisation of a database at the same time.
Working alongside this I've remembered ii dissimilar solutions summation I've learned or as well as then other one:
1.) Using synchronized keyword inwards a method. This is what I've used, because fortunately all my spider web service calls are inwards a unmarried class. Basically it locks the method as well as solely 1 thread tin access the method at a time.
public synchronized ClientResponse syncWebServiceCall( WebResource webResource) { // code hither }
2.) The side past times side is a contestation block, like to no 1 except that yous used a mutex object to lock. The mutex object tin travel the object where the method is defined or or as well as then other object. In this trend nosotros don't necessarily lock the whole method.
public ClientResponse syncWebServiceCall( WebResource webResource) { synchronized(this) { // code } }
3.) The finally one. Which I've simply learned. Using ReentrantLock: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html Modifying the example:
class X { mortal concluding ReentrantLock lock = novel ReentrantLock(); populace ClientResponse syncWebServiceCall() { lock.lock(); // block until status holds effort { // ... method trunk } finally { lock.unlock() } } }
0 komentar:
Please comment if there are any that need to be asked.