我用Java RMI开发了一个简单的不可信系统,现在我必须将其更改为Web Services。我的数据结构有问题:
Hashtable<String, ArrayList<Records>> recordsTable;
它无法正确序列化/更新我的对象。
我不知道如何改变我的数据结构来克服这样的问题?
[已编辑]
为了简单起见,假设我有这个数据结构:
Hashtable<String, Integer> store = new Hashtable<String, Integer>();
我有一个已发布的 buy() 和 display() 服务。最初我的商店里有 100 个苹果,所以当我 buy() 10 个苹果时,它会打印 90 个苹果的结果。 但是当我稍后调用显示时,它将打印 100 个苹果。
所以存在序列化问题,我不知道如何解决。
public class StoreServer{
Hashtable<String, Integer> store= new Hashtable<String, Integer>();
public StoreServer()
{
store.put("Coffee", 20);
store.put("Apple", 100);
store.put("Banana", 50);
display();
}
public String buy(String item, int quantity)
{
if(store.containsKey(item))
{
int oldQuantity = store.get(item);
int newQuantity;
if(oldQuantity-quantity>=0)
{
newQuantity= oldQuantity -quantity;
store.put(item, newQuantity);
return quantity+" "+item+" were successfully purchased!\n" +
("1. Coffee: "+store.get("Coffee")+"\n")+
("2. Apples: "+store.get("Apple")+"\n")+
("3. Bananas: "+store.get("Banana")+"\n")+
("---------------------------\n");
}
else
{
return "error with your purchase";
}
}
else
{
return "error with your purchase";
}
}
public void display()
{
System.out.println("------Store Inventory-----");
System.out.println("1. Coffee: "+store.get("Coffee"));
System.out.println("2. Apples: "+store.get("Apple"));
System.out.println("3. Bananas: "+store.get("Banana"));
System.out.println("---------------------------");
}}
最佳答案
Web 服务使用无状态协议(protocol)。您需要将存储 HashMap 设置为静态。
另外,请确保它是 ConcurrentHashMap,因为它可能会被多个线程同时访问。
关于java - WebService java 中的哈希表更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19727598/