| Author |
synchronize block of code in multiple JVM instances
|
vittal mareddy
Greenhorn
Joined: Jul 24, 2011
Posts: 14
|
|
I have a servlet code, synchronized the code using synchrozie block, it is working if i use single instace of web server(tomcat), all threads accessing same code are synchronized, whereas same code if i deploye in load balanced environement 2 application servers(each 2 jvms ) i.e total 4 JVMs, synchronization is failing.
Load balanced environement(websphere application server version 7.0.0.13).
here is sample code
protected String instantiateObject(
synchronized(Sample.class){
//logic insert data to be synchrozied
}
}
I see from other supporting forums, synchronization across multiple jvs can be achieved using
file object then filechannel and lock on it. please let me know.
public synchronized void mymethod() throws Exception {
RandomAccessFile raf = new RandomAccessFile("mylock","rw");
FileChannel fc = raf.getChannel();
fc.lock(); // this will block if the lock can't be obtained
// login for insert information
fc.close(); // end the block and unlock raf.close();
}
I am not sure this approach will work, or anything more i have to do.
|
 |
Michael Ernest
High Plains Drifter
Sheriff
Joined: Oct 25, 2000
Posts: 7292
|
|
Hello Vittal -
In order to synchronize threads in different JVMs, there has to be some external object to act as a guard for the resource you want to protect from unsynchronized access. All participating JVMs have to agree on this mechanism and have to use it properly. A disk-based object like a file is a typical choice, but there are other possibilities: a database record, or a serializable token that is passed among the JVMs, etc. But in each case, there has to be some thing the JVMs can use to arbitrate access to shared data.
|
Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
|
 |
vittal mareddy
Greenhorn
Joined: Jul 24, 2011
Posts: 14
|
|
I was trying, as below to synchronize execution in multiple jvms and multi thread invocation, i can see inconsistance, do i need to change anything or any suggestions please help me.
|
 |
Maarten Bodewes
Greenhorn
Joined: Aug 04, 2011
Posts: 14
|
|
|
Don't try and create locks on remote files, use something else, e.g. a database for synchronization (or try and work around your sync options).
|
 |
Chris Hurst
Ranch Hand
Joined: Oct 26, 2003
Posts: 370
|
|
Other technologies to do this do exist but it would depend very much on your circumstance ...
As an example you could run your JVM's on terracotta in which case the code as you initially described can work. terracotta
Other good shared cache technologies do exist ;-) , again it depends on your circumstance and/or what shared resources are available, a shared database is another common solution.
|
"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
|
 |
 |
|
|
subject: synchronize block of code in multiple JVM instances
|
|
|