问题
Imagine having a webservice
or servlet
, which can perform some fileIO
.
How can I make sure that if more than one client executes the according WS method, that the fileIO is still handled only by one single "thread"? So that no data is lost because several clients trigger the fileIO?
Which direction should I search for?
回答1:
The best bet is likely to just make the underlying method(s) that read/write synchronize on a common object. (eg. the File object could be easiest).
private static File theFile = new File("theonetoopen.txt");
...
private void someImportantIOMethod(Object stuff){
synchronized(theFile){
//Your file output writing code here.
}
}
来源:https://stackoverflow.com/questions/11957927/shared-servlet-for-fileio