2010-05-03 19 views
0

我想在JNDI中放置一個對象,以便只有一個程序應該能夠將它放在JNDI中。有沒有可以在J2EE環境中使用的全局鎖? RMI是否可以用於此目的?請提供任何參考鏈接。提前致謝。如何同步跨進程在JNDI中放置對象?

另外,什麼是NameAlreadyBoundexception?我試圖將它用作同步的一種方法,即只有一個程序將它放入JNDI,並且如果其他嘗試綁定的應用程序應該得到該異常。 但是,當我測試多重綁定我沒有得到Exception.And第二個綁定完成。仰望是給第二個對象綁定。這裏是我的代碼:

public class TestJNDI { 
private static String JNDI_NAME = "java:comp/env/test/something"; 

    public static void main(String[] args) throws NamingException { 

     Hashtable<String, String> env = new Hashtable<String, String>(); 
     env.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory"); 
     env.put(Context.PROVIDER_URL,"t3://127.0.0.1:7001"); 

     Context ctx = new InitialContext(env); 
     System.out.println("Initial Context created"); 

     String obj1 = "obj1"; 
     String obj2 = "obj2"; 

     try{ 
      ctx.bind(JNDI_NAME, obj1); 
      System.out.println("Bind Sucess"); 
     }catch(NameAlreadyBoundException ne){ 
     // already bound 
     System.out.println("Name already bound"); 
     } 


    ctx.close(); 

    Context ctx2 = new InitialContext(env); 
    try{ 
     // Second binding to the same name not giving the Exception?? 
     ctx2.bind(JNDI_NAME, obj2); 
     System.out.println("Re Bind Sucess"); 
     }catch(NameAlreadyBoundException ne){ 
    // already bound 
    System.out.println("Name already bound"); 
     } 


    String lookedUp = (String) ctx2.lookup(JNDI_NAME); 

    System.out.println("LookedUp Object"+lookedUp); 
    ctx2.close(); 
    } 


} 

回答

0

當您關閉第一個內容ctx1你釋放綁定到任何對象,請參閱:Context

所以你的第二個上下文無關與第一個。