簡體   English   中英

Java RMI對象是靜態字段還是非靜態字段?

[英]Java RMI object static and not static field?

所以我有這段代碼:

public class RemoteImpl extends UnicastRemoteObject implements TestRemote {

    private static final long serialVersionUID = 1L;
    private static int counter = 0;
    private int localizedCounter = 0;

    protected RemoteImpl() throws RemoteException {
        super();
    }

    @Override
    public int getMeGlobalCounter() throws RemoteException {
        counter++;
        return counter;
    }

    @Override
    public int getMeLocalizedCounter() throws RemoteException {
        localizedCounter++;
        return localizedCounter;
    }
}

與我的客戶一起,我正在嘗試:

public class TestClient {

    public static void main(String[] args) throws Exception {
        Registry registry = LocateRegistry.getRegistry("localhost", Constant.RMI_PORT);
        TestRemote remote = (TestRemote) registry.lookup(Constant.RMI_ID);
        System.out.println("Global counter:" + remote.getMeGlobalCounter());
        System.out.println("Localized counter:" + remote.getMeLocalizedCounter());
    }

}

在兩次運行此代碼后,我希望看到:

Global counter:3
Localized counter:1

但是我看到

Localized counter:3

那么,為什么每次調用此方法時都不會重置本地化計數器? 我不是每次都得到一個新物體嗎?

我不是每次都得到一個新物體嗎?

不,你不是。 您將獲得綁定到注冊表中的同一實例。 RMI不僅會隨意創建遠程對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM