我创建了一个使用JSCH库读取和写入远程位置属性文件的应用程序。如何使用java同步文件操作?同步或锁定?
我想同步写入操作。
这是我的代码,
class WebApp{
private String webappName;
private boolean isQA = false;
private String path ;
public WebApp(String name , String path , boolean isQA){
this.webappName = name;
this.path = path;
this.isQA = isQA;
}
public String getWebappName() {
return webappName;
}
public void setWebappName(String webappName) {
this.webappName = webappName;
}
public boolean isQA() {
return isQA;
}
public void setQA(boolean isQA) {
this.isQA = isQA;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
class WebAppProperty implements Runnable{
private WebApp webapp; // webapp-1
private String propertyFile; // server.properties
private String keyValue;
public String getPropertyFile() {
return propertyFile;
}
public void setPropertyFile(String propertyFile) {
this.propertyFile = propertyFile;
}
@Override
public void run(){
writeToPropertyFile();
}
public WebAppProperty(WebApp webapp , String propertyFile,String keyValue){
this.webapp = webapp;
this.propertyFile = propertyFile;
this.keyValue = keyValue;
}
private void writeToPropertyFile(){
try{
// code for writing key value pair into remote file
}catch (Exception e) {
}
}
}
这就是我想要
如果用户试图写入到Web应用程序属性文件中说,“A”,其他所有用户谁试图写入同一个webapp的相同文件应该等待,但另一个用户可以在另一个webapp上写入同一web应用或同名文件的另一个文件。
同步方法可以完成所有这些工作吗?它如何识别webapp和属性文件?
我们是否需要同步读取和写入操作?
如何在此场景中实现锁定?
注:我看到了有关并发不同的问题,但这些都没有使我不再怀疑这就是为什么我提出新的问题,请大家帮我得到这个
编号'synchronized'不会帮助。你选择限制你选择的方法。只有我看到的是“锁定”文件。您应该检查该特殊文件是否存在,如果它没有创建它,请修改您的属性文件并删除“锁定”文件。 – talex
@talex我已经检查了锁的实现,只是如何混淆就像如何锁定在同一个文件上的写操作?意思是如果一个线程试图写入文件A没有其他线程可以写入文件A,但它应该能够写入除文件A以外的其他文件。如何通过使用Lock来实现?我的理解是,我们可以锁定我们正在执行的操作 –
@AnsarSamad你可以分享你创建WebAppProperty实例并运行它的部分吗? –