About
In my servlet,I have annon-accessible-constructor-class EncryptHelper
(which is used to encrypt some data before submit) with a static methodbooleanstatic encrypt(String msg)
.
Every client will invoke EncryptHelper.encrypt(String msg) to encrypt their message before submit.
In this case,should i synchronize
this method to provide a concurrence invoking? Or should i let it be it's used to be?
Can anyone tell me why and how i should do?
[560 byte] By [
johnnylzba] at [2007-10-2 14:25:27]

> Oh? Not synchronized? Then if several threads invoke
> the doPost() simultaneously,what will happen?
Several threads begin executing the doPost method.
This is an issue only if there is Class Member data, which is a bad idea:
For example:
public class BadServlet ... {
private Object shareMe = new SomeObject(42, "Hellow", 'W', 'o', 'r', 'l', 'd');
public void doPost ( ... ) {
doSomethingWith(shareMe);
...
}
//as opposed to:
public class BetterServlet ... {
//no class members
public void doPost(...) {
Object shareMe = new SomeObject(42, "Hellow", 'W', 'o', 'r', 'l', 'd');
doSomethingWith(shareMe);
}
In Servlets, since there may be many connections to the server, and requests may take some time, it is best to try to reduce the need for shared data, and therefore synchronization. Create objects inside the doXxx methods when you can, so that each Thread has its own copy and syncs aren't needed. If you do need to share objects, use a seperate method to grab a COPY of the data that you will work on. Sync that copying method, not the doPost. Then sync a method to copy the data back to the shared object:
public class OKServlet ... {
private Object shareMe ...
//just used as a lock for syncs
private Object shareMeLock = new Object();
public void doPost (...) ... {
Object copyOfShareMe = getShareMe();
processShareMe(copyOfShareMe);
saveChanges(copyOfShareMe);
}
private Object getShareMe() {
Object copy = null;
synchronize(shareMeLock) {
copy = shareMe.clone();
}
return copy;
}
private void saveChanges(Object copy) {
synchronize(shareMeLock) {
shareMe.fillInChanges(copy);
}
}
...
}