明智地创建新对象并使用相同的对象实例而不是创建新对象是明智的。在下面的情况下,我对确定创建对象的解决方案并不十分有信心。有一个SOAP服务类有几种方法来负责多个客户。请参阅模板下面,Java设计模式:Factory vs Singleton?在多线程的情况下
Public class SOAPService {
public Object getProductList(String CustId, String endPoint){
SOAPStub stub = new SOAPStub(endPoint);
Object productList = stub.getProductList();
return productList;
}
public Object getProductInfo(String CustId, String productId, String endPoint){
SOAPStub stub = new SOAPStub(endPoint);
Object productInfo = stub.getProductList(productId);
return productInfo;
}
}
现在我介绍一个工厂方法为每个客户创建对象,并把它放在一个地图,但我很困惑,当单个客户的多个线程将访问该服务类。对象的行为不会像单身或可能导致任何死锁问题,或让线程等待?请在此指导我。
Public class SOAPService {
private Map<String, SOAPStub> map = new HashMap<String, SOAPStub>();
public SOAPStub getSOAPObject(String CustId, String endPoint){
if(map.containsKey(CustId))
return map.get(CustId);
else{
SOAPStub stub = new SOAPStub(endPoint);
map.put(custId, stub);
return stub;
}
}
public Object getProductList(String CustId, String endPoint){
SOAPStub stub = getSOAPObject(CustId, endPoint);
Object productList = stub.getProductList();
return productList;
}
public Object getProductInfo(String CustId, String productId, String endPoint){
SOAPStub stub = getSOAPObject(CustId, endPoint);
Object productInfo = stub.getProductList(productId);
return productInfo;
}
}
这是一个很好的解决方案,但是如果同一个对象的两个线程发送请求 – Bibhaw
请不要延迟响应请扩展您的问题。你认为可能会延迟到哪里? –
Eugene,假设我有一个customer_1,其中2个请求线程同时分派,并且假设Thread_1请求正在处理中,并且thread_2将等待对象实例,直到thread_1完成并释放任务。这就是我想说的对线程2的响应延迟。 但是当我们有一个系统为每个请求创建对象时,Thread-1和thread_2请求将拥有自己的对象,并且不需要等待释放该对象。你说的话 ? – Bibhaw