Syncronization use in HashTable?

Hi,
we know HashTable is syncronized.....it is used to save object by using key value pair rite?then here what is advantage of syncronization?

I'm not sure you 'get' synchronization.
If you use a basic non-syncrhonized java.util.Map, then if one thread adds something, and in the middle of the adding process, another thread also adds something to the same map, the entire thing will be an invalid error-causing bug-ridden mess from there on out, because its internal state is corrupt (ie: the internal 'size' cache doesn't match the actual number of objects stored in the Map, entire parts of the tree can magically disappear, etcetera).
Hashtable simply prevents the Map from becoming corrupted when you do that, BUT, it costs you CPU speed. Even if only 1 thread even has a reference to the Map.
Regardless, Hashtable is sort of outdated. Just use a HashMap (or TreeMap, or some other sort of relevant Map) and if you need to secure it it against corruption due to access by multiple threads, run it through Collections.synchronizedMap(). ie:
Map<Integer, String> myMap = Collections.synchronizedMap(new HashMap<Integer, String>());
That will end up being far more flexible. What if later you figure out you need your map sorted, so you have to go for a TreeMap? There's no child of Hashtable that does sorting.

Similar Messages

  • Should I use a Hashtable ?

    I need to implement an orderdered list of objects (essentialy a queue). I estimate the maximum size of the list to be 2 million objects!
    Through out the processing of my application I will need to insert objects at various locations through out the list.
    I am thinking a vector is not going to be appropriate for this? I have not used a Hashtable before but from what I have read it speeds up access to large volumes of data by indexing them?
    I have been considering storing the objects as records in a database but accessing objects 1 at a time (all objects will need to be accessed) is not a good strategy as far as query overhead is concerned.
    Your ideas are very much appreciated!
    John

    Lets say an object is 100 Byte. 1.5 million of them is 150 MByte of memory. An index is 1.5 million * 4 Byte (an address ) = 6 MByte at a minimum. Lets say 50 to be sure (it should accomodate a tree). You'll need 150 MByte for the data and 50 MByte per index you want to keep. Data plus 2 indicies is 250 MByte plus 250 Mbyte for the program is 500 MByte. Double that to 1 GByte to be on the safe side and voila you have a very fast in-memory pure Java solution for your problem. It will take you about 1 GByte of memory but that's no big deal today.

  • Need to run a prog on 1.4 which is running on 1.5. .....using two hashtable

    hello,
    I've developed a program which is prefectly working on java 1.5.0 version.
    but when run on java1.4.0. it gives run time error in this code.
    first i'm getting error in second hashtable. put function where i'm using key as an integer.this is running on 1.5 version but have to change key as string on 1.4. but after that it is still not working properly.
    I want that when i clicked on open then it must show both file
    1. that have hdr extension
    2. that have same name as the corrseponding .hdr file but without extension.
    this program show desired result on 1.5 but on 1.4 it display only .hdr file.
    pls. help me regarding this .
    // class hdr file filter
    import java.io.File;
    import java.util.Hashtable;
    import java.util.Enumeration;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class hdrFileFilter extends FileFilter {
    private Hashtable filters = null;
    private Hashtable noextensionfilter = null;
    private String noextensionname=null;
    private String extensionname = null;
    private String description = null;
    private String fullDescription = null;
    private boolean useExtensionsInDescription = true;
    private String fname = null;
    public File noextensionarray[];
    int count=0;
    int counthdr=0;
    int i=0;     
         //all files are accepted.
    public hdrFileFilter()
         this.filters = new Hashtable();
         //Creates a file filter that accepts files with the given extension.
    public hdrFileFilter(String extension)
         this(extension,null);
         //Creates a file filter that accepts the given file type.
    public hdrFileFilter(String extension, String description)
         this();
         if(extension!=null)
         addExtension(extension);
         if(description!=null) setDescription(description);
         //Return true if this file should be shown in the directory pane,false if it shouldn't.
    public boolean accept(File f) {
         if(f != null) {
         if(f.isDirectory()) {
              return true;
         String extension = getExtension(f);
         if(extension != null && filters.get(getExtension(f)) != null)
              fname=f.getName();
              extensionname=fname.substring(0,fname.lastIndexOf('.'));
              counthdr+=1;
              return true;
         if(extension == null)
              noextensionfilter=new Hashtable(20);
              noextensionname=f.getName();          
              noextensionfilter.put(count,noextensionname);
              count=count + 1;
              if(noextensionfilter.get(count) == extensionname)
                   noextensionarray=new File[20];
                   noextensionarray=f
                   System.out.println("file:" +noextensionarray[i]);
                   i++;
                   return true;               
         return false;
         //Return the extension portion of the file's name .
    public String getExtension(File f)
              if(f != null)
                   String filename = f.getName();
                   int i = filename.lastIndexOf('.');
                   if(i>0 && i<filename.length()-1)
                        return filename.substring(i+1).toLowerCase();
              return null;
         //Adds a filetype "dot" extension to filter against.
    public void addExtension(String extension)
         if(filters == null)
         filters = new Hashtable(20);
         filters.put(extension.toLowerCase(), this);
         fullDescription = null;
    public String getDescription()
              if(fullDescription == null)
                   if(description == null || isExtensionListInDescription())
                        fullDescription = description==null ? "(" : description + " (";
                        // build the description from the extension list
                        Enumeration extensions = filters.keys();
                        if(extensions != null)
                             Object nn=extensions.nextElement();
                             fullDescription += "." + nn;     
                             while (extensions.hasMoreElements())
                                  fullDescription += ", ." + nn;
                        fullDescription += ")";
                   else
                        fullDescription = description;
              return fullDescription;
    public void setDescription(String description)
         this.description = description;
         fullDescription = null;
    public void setExtensionListInDescription(boolean b) {
         useExtensionsInDescription = b;
         fullDescription = null;
              public boolean isExtensionListInDescription()
              return useExtensionsInDescription;

    Might be fixable if you do something like
    javac -target 1.4
    Bytecodes are different in 1.5 and thus not backward compatible

  • Use of Hashtable in a JSP

    I have a JSP page, displaying Employee details(5 attrbutes in total)
    (code, name, address, telephone, email)
    And this employee is coming from Employee table, which is having around 50 attributes, and I have one entity class for the employee doing the database operation.
    Now since I have to show only 5 fields, using Employee class (which is having 50 attributes) will be very heavy.
    Should I create a new bean class EmployeeView having only 5 attributes or shall i go for <b>hashtable</b> , having 5 entries, with attribute name as key and attribute value as key value.
    Are there any disadvantage on using hashtable like this, or what can be better approach.
    Please suggest.

    Hi,
    The best way for this is to create view for the table in the database.
    Then you can access the view like how you access a table.
    This will reduce the amount of data transfer from database to your application.
    Hope this helps.
    Good Luck.
    Gayam.Srinivasa Reddy
    Developer Technical Support
    Sun Micro Sysytems
    http://www.sun.com/developers/support/

  • Using a Hashtable

    i want to use a lookup or hashtable to store the values of the cards which are randomly dealt for each hand, be able to see how many for each card value there are in the hash table, and if there are more than 3 for a particular value, i want it to increment the count value of 3 of a kinds by one, then i want to clear the table and loop it all over again.
    my many thanks in advance
    Objective: To answer the question:- What is the likelihood of getting
    'three of a kind' in a hand of five cards dealt from a standard pack of 52
    playing cards?
    import java.util.Vector;
    import java.util.Arrays;
    import java.lang.String;
    import java.util.Random;
    import java.util.Hashtable;
    import Card;
    import Pack;
    public class PokerTester {
    // create a pack
    public static void main(String[] args) {
    Hashtable values = new Hashtable();
    values.put("Ace", new Integer(0));
    values.put("Two", new Integer(0));
    values.put("Three", new Integer(0));
    values.put("Four", new Integer(0));
    values.put("Five", new Integer(0));
    values.put("Six", new Integer(0));
    values.put("Seven", new Integer(0));
    values.put("Eight", new Integer(0));
    values.put("Nine", new Integer(0));
    values.put("Ten", new Integer(0));
    values.put("Jack", new Integer(0));
    values.put("Queen", new Integer(0));
    values.put("King", new Integer(0));
    int numbDeals = 10;
    Pack p = new Pack();
    Card[] hand = new Card[5];
    for (int j = 0; j < 10; j++) {
    for (int i = 0; i < 5; i++) {
    hand = p.drawCard();
    System.out.println("We got a: "+hand);
    System.out.println("There are "+p.size()+" cards left");
    System.out.println(values);//prints what is in the hashtable

    So which looks easier:
    int count3OfAKinds = count3( hand );
    Integer count = (Integer)hash.get("3OfAKind");
    count = new Integer( count.intValue() + count3OfAKinds );
    hash.put( "3OfAKind", count );or
    this.threeOfAKind += count3( hand );My point is that sometimes simpler is better. If you don't need the functionality of a hash, then don't use it.

  • Struts - example of iterate using a hashtable (key,value)

    I am trying to create a dynamic menu system and each menu group
    is storied within a single hashmap with the name of the menu as the key (e.g. "mainmenu", "adminmenu"). I am having problems understanding the documentation on how to pass the key to select the
    right entry within the hashmap. I have read the following but find
    it confusing. Could someone provide a detailed example?
    http://jakarta.apache.org/struts/struts-logic.html#iterate

    Here's some code to show you what I am doing.
    I will start out with how I am creating the List and the HashMap
        menuList = new ArrayList();
        sqlStatement = "select * from menu where admin = 'Y' ";
        // gets the menu items from the database and builds the menuList
        this.buildMenu( (DBResultSet)db.executeSQL( sqlStatement, args ) );
        // puts the menuList into a HashMap with a key of adminmenu
        //  NOTE: the menuList is actually a collection (list) of beans
        menuMap.setItem ("adminmenu", menuList );
        ...Here's my bean that stores I use to store the HashMap (menuMap).
    import java.util.*;
    public class MenuBO extends BaseBusinessObject
      private HashMap menuMap;
      public MenuBO()
        menuMap = new HashMap();
      public void setItem ( String menuType, List menuList )
        menuMap.put ( menuType, menuList);
      public List getItem( String menuType )
        return  (List)this.menuMap.get( menuType ) ;
      public HashMap getMenuMap ()
        return menuMap;
      public void removeItem ( String menuType)
        menuMap.remove( menuType);
    }And here's my iterate which is not working. I want to single out the value that has a key of "adminmenu" and process that list of menu elements. This is easy to do with scriptlets but I am spending many hours trying to figure out Struts documentation - they need some real world examples if they want Struts to catch on...
    <jsp:useBean id="menuMap" scope="session"
              class="com.benchdogs.webapp.beans.MenuBO"/>
            <logic:iterate id="mapEntry" name="menuMap" property="menuMap">
                <bean:write name="mapEntry" property="key"/>
            </logic:iterate>This example loops through the hashmap and displays the keys. I want to be able to process a specific value based on the key. The value is a List so I would need to do another iterate statement within the master iterate.

  • Need help in using hashtable as a property of a form bean

    Hi,
    Is it possible to use a hashtable as a property of the bean.
    Well this is the problem i have
    I am using a hashtable as property and i want it to store from(/retrive into} form as ints/strings
    I have a
    JSP Page
    SampleAction --Action
    SampleForm --ActionForm
    Sample(bean)
    =============
    JSP Page
    (within the html:form tag)
    <html:text property="sample.number" />
    ====================
    struts-config links to
    SampleAction
    SampleForm
    ==============
    SampleForm
    Sample sample = new Sample();
    reset(){ ...impl...}
    validate(){.... impl.....}
    =================
    Sample.java
    private Hashtable prop = new Hashtable();
    public int getNumber()
       return ((Integer)prop.get("number")).intValue();
    public void setNumber(int number)
       prop.put("number",new Integer(number));
    ====================================
    this setup understandbly gives me a error like this
    no getter method for property sample.number
    PLEASE DO remember that i have a large number of mixed types in my form that needs to be populated into the bean and i detest using that many variables(in the bean)
    I NEED TO A KNOW A SOLN. PLEASE
    Thanx in advance
    cheers
    Ash

    Hi,
    I think the solution for your problem is
    put a form tag in your jsp page.
    name it as your form name defined in the struts-config.xml.
    in your case
    it is 'sample'.
    And make changes in the html:text tag like,
    <html:text name="sample" property="number" />
    Hope it will work.. have fun !!!

  • Use of primitive datatypes as hashtable key finally OK?

    Are we finally at the point where we can use primitive values as keys in a hashtable? I know that this wouldn't work in the past, and I haven't needed to use a hashtable for years, so I haven't really cared.
    Yesterday I tried it in a program compiled for JVM 1.5, using ints for the keys, and it runs fine. Admittedly, I do get several "unchecked operation" warnings during compilation.

    Yesterday I tried it in a program compiled for JVM
    1.5, using ints for the keys, and it runs fine.
    Admittedly, I do get several "unchecked operation"
    warnings during compilation.It autoboxed the ints as Integers for you. Under the covers it is still using Integer objects.

  • Fill combobox from CSV using hashtable

    Hi, i created a simple windows form with a combobox that i im trying to fill with the full name column in my csv and i want it to return the  abreviated name column value in a variable so i used a hashtable and added both columns, but after selecting
    an item from the combobox, the $namehash[$return] is null. Shouldnt it return the abreviated name?
    My csv is comma seperated
    Name, Shortname
    Michigan,MI
    Ohio,OH
    Import-Module Activedirectory
    function button ($WF) {
    ###################Load Assembly for creating form & button######
    [void][System.Reflection.Assembly]::LoadWithPartialName( “System.Windows.Forms”)
    [void][System.Reflection.Assembly]::LoadWithPartialName( “Microsoft.VisualBasic”)
    #####Define the form size & placement
    $form = New-Object “System.Windows.Forms.Form”;
    $form.Width = 500;
    $form.Height = 190;
    $form.Text = $title;
    $form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen;
    $form.ControlBox = $True
    ##############Define text label2
    $textLabel2 = New-Object “System.Windows.Forms.Label”;
    $textLabel2.Left = 25;
    $textLabel2.Top = 80;
    $textLabel2.Text = $WF;
    ############Define text box2 for input
    $cBox2 = New-Object “System.Windows.Forms.combobox”;
    $cBox2.Left = 150;
    $cBox2.Top = 80;
    $cBox2.width = 200;
    ###############"Add descriptions to combo box"##############
    $NameHash = @{}
    import-csv 'C:\temp\test_cidb.csv' | ForEach-Object {
    $cBox2.Items.Add($_.Description)
    $NameHash.Add($_.Name,$_.Shortname)
    ############Define text box3 for input
    #############Define default values for the input boxes
    $defaultValue = “”
    $cBox2.Text = $defaultValue;
    #############define OK button
    $button = New-Object “System.Windows.Forms.Button”;
    $button.Left = 360;
    $button.Top = 45;
    $button.Width = 100;
    $button.Text = “Ok”;
    $Button.Cursor = [System.Windows.Forms.Cursors]::Hand
    $Button.Font = New-Object System.Drawing.Font("Times New Roman",12,[System.Drawing.FontStyle]::BOLD)
    ############# This is when you have to close the form after getting values
    $eventHandler = [System.EventHandler]{
    $cBox2.Text;
    $form.Close();};
    $button.Add_Click($eventHandler) ;
    #############Add controls to all the above objects defined
    $form.Controls.Add($button);
    $form.Controls.Add($textLabel2);
    $form.Controls.Add($cBox2);
    $ret = $form.ShowDialog();
    #################return values
    return $cbox2.text
    $return= button “Job Descriptions"

    I solved my own issue by creating a datatable using that as the data source and binded the combobox using displaymember, valuemember, datasource classes. Exactly what I was wanting do do.
    $reader = new-object System.IO.StreamReader($csvfile)
    $line = $reader.ReadLine()
    $columns = $line.Split($csvdelimiter)
    foreach ($column in $columns) {$null = $datatable.Columns.Add($column) }
    while (($line = $reader.ReadLine()) -ne $null) {
    $row = $datatable.NewRow()
    $row.itemarray = $line.Split($csvdelimiter)
    $datatable.Rows.Add($row)
    $cbox2.DisplayMember = "Name"
    $cbox2.ValueMember = "Shortname"
    $cbox2.DataSource = $datatable
    $States=cbox2.SelectedValue

  • NEED HELP WITH WORD & CHAR COUNT USING HASHTABLE

    I have to use a hashtable to be able to count all the words and characters (#'s, punctuations, etc) from a file
    I have been able to get it to correctly count the words in the file but none of the characters and it also does not display the words alphabetically and just displays it in an odd way
    Here's the code: public static void main (String [] args)
          Hashtable table = new Hashtable();
          String input = JOptionPane.showInputDialog("Enter the filename:");
          try{
          BufferedReader br = new BufferedReader(new FileReader(input));
          String s = br.readLine();
          StringTokenizer words = new StringTokenizer( s, " \n\t\r" );
            while ( words.hasMoreTokens() ) {
             String word = words.nextToken().toLowerCase(); // get word
             // if the table contains the word
             if ( table.containsKey( word ) ) {
                Integer count = (Integer) table.get( word ); // get value
                // and increment it
                table.put( word, new Integer( count.intValue() + 1 ) );
             else // otherwise add the word with a value of 1
                table.put( word, new Integer( 1 ) );
           } // end while
             String output = "";
          Enumeration keys = table.keys();
          // iterate through the keys
          while ( keys.hasMoreElements() ) {
             Object currentKey = keys.nextElement();
             output += currentKey + "\t" + table.get( currentKey ) + "\n";
             System.out.println(output.toString());
          catch (IOException e)
            System.out.println(e);
          }The output that I get for a file containing the line " Hi this is my java program" is:
    this     1
    this     1
    program     1
    this     1
    program     1
    hi     1
    this     1
    program     1
    hi     1
    java     1
    this     1
    program     1
    hi     1
    java     1
    is     1
    this     1
    program     1
    hi     1
    java     1
    is     1
    my     1
    I'm not sure what I am doing wrong and help would be greatly appreciated.

    I have been able to get it to correctly count the
    words in the file but none of the characters and it
    also does not display the words alphabetically and
    just displays it in an odd way
    That's because hash tables are not ordered; to maintain order of insertion you could use LinkedHashMap and to maintain alphabetical order TreeMap.

  • Can I send a Java HashTable using IDL and CORBA?

    I have code that uses a HashTable implementation of the Map datatype. I would like to be able to send this datatype using IDL and CORBA without trying to map it to Struct, if at all possible. I have just started with this yesterday, IDL that is, have successfully run the Hello World over the network and passed a string variable instead of just the string, and would welcome any help whatsoever.
    Thanks,
    Teresa Redmond

    - Don't transfer the Hashtable at all, but writea
    server, which gives access to the Hashtableentries
    I think what Martin means is: why not let yourserver
    actually do the work with the Hashtable in itself
    instead of making the client do it?
    Yes, exactly this is what I meant. And I will
    strengthen your arguments, why building a server for
    the Hashtables would probably be the best solution. So
    first double-check, whether you can go this way,
    before reading any further!
    But anyway, if you want to look deeper into
    serialization:
    - Create an ObjectOutputStream consisting of a
    ByteArrayOutputStream:
    ByteArrayOutputStream baos = new
    ByteArrayOutputStream(100);
    ObjectOutputStream oos = new
    ObjectOutputStream(baos);where "100" is the initial size in bytes.
    - Write to this stream with
    oos.writeObject(hashtable);
    oos.flush();- Send the data as a sequence of bytes, which can be
    accessed by:
    baos.toByteArray()- on the receiving side, create an ObjectInputStream
    from the received byteArray:
    ByteArrayInputStream bais = new
    ByteArrayInputStream(byteArray);
    ObjectInputStream ois = new
    ObjectInputStream(bais);- Then read the hashtable:
    Hashtable h =
    (Hashtable)ois.readObject();This is only a very coares description of the process,
    but should just give some pointers to the basic way to
    serialization.So, in the client, I could:
    Map m = new HashMap();
    //fill m
    baosSize = m.getsizeofm();//pseudo method
    ByteArrayOutputStream baos = new ByteArrayOutputStream(baosSize);
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(m);
    oos.flush();
    baos.toByteArray()and in the server code, I could:
    ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
    ObjectInputStream ois = new ObjectInputStream(bais);
    Map mh = (HashMap)ois.readObject();is that about right? If that's the case, how do I write the idl file? is this a string? say, "string baos;"?
    Thanks, guys, I really appreciate your help!

  • Using a string to reference a variable

    hi all,
    i've encountered an interesting scenario where i need to use a string to reeference the value of a variable...the following would show the scenario in a simpler way...
    let's say we have such function called foo:
    void foo(String aString)
    int a = 20;
    int b = 20;
    system.out.println(?????);
    now let's say i run the function as:
    foo("a")
    and i want it to return:
    20
    what should be put to replace those "?????" in my function above?
    please note that variables "a" and "b" are arbitary and so having a conditional statement like the following would NOT be useful:
    void foo(String aString)
    int a = 20;
    int b = 20;
    if (aString.equals("a"))
    system.out.println(a);
    if (aString.equals("b"))
    system.out.println(b);
    thank you very much!

    There are two possibilities here.
    The preferable one, if you have control over the names and nature of the variables, then don't use individual variables - use a Hashtable (or any implementation of Map). Your code would then look something like:void foo(String aString)
        Map table = new Hashtable();
        table.put("a", new Integer(20));
        table.put("b", new Integer(30));
        system.out.println(table.get(aString));
    }The down side to this is that you have to use Integers - Maps can't take primitives.
    If, on the other hand, you have to have variables, then take a look at using reflection. It's more complicated than using Maps, and less efficient, so I would recommend the first technique if possible.
    RObin

  • HOWTO: Using a BC4J Application Module in an Stateless EJB Session Bean

    HOWTO: Using a BC4J Application Module in an Stateless EJB Session Bean
    by Steve Muench
    Overview
    BC4J provides automatic facilities for deploying any application module as a stateful EJB session bean. If you want to leverage the features of your BC4J application module from a stateless EJB session bean, it's not automatic but it is straightforward to implement. This howto article explains the details.
    For our example, we will create a stateless EJB session bean that uses a container-managed transaction. To keep things simple, let's assume the session bean has a single public method on its remote interface named createDepartment() with the following signature:
    public void createDepartment(int id, String name, String loc) throws AppException
    AppException is an example of an application-specific exception that our method will throw if any problems arise during its execution.The goal of this article is to illustrate how to use the BC4J application module named com.example.hr.HRApp as part of the implementation of this createDepartment method on our stateless enterprise bean. Let's assume that the HRApp application module has a view object member named Departments, based on the com.example.hr.DeptView view object, based on the familiar DEPT table and related to the com.example.hr.Dept entity object so our view can be updateable.
    Creating the Stateless Session Bean
    We can start by using the JDeveloper Enterprise Bean wizard to create a new stateless session bean called StatelessSampleEJB implemented by:[list][*]com.example.StatelessSampleEJBBean (Bean class)[*]com.example.StatelessSampleEJBHome (Home interface)[*]com.example.StatelessSampleEJB (Remote interface)[list]
    We then use the EJB Class Editor to add the createDepartment method to the remote interface of StatelessSampleEJB with the signature above. We edit the remote interface to make sure that it also reflects that the createDepartment method thows the AppException like this:
    package com.example;
    import javax.ejb.EJBObject;
    import java.rmi.RemoteException;
    public interface StatelessSampleEJB extends EJBObject {
      void createDepartment(int id, String name, String loc)
      throws RemoteException,AppException;
    }Before we start adding BC4J into the picture for our implementation, our StatelessSampleEJBBean class looks like this:
    package com.example;
    import javax.ejb.SessionBean;
    import javax.ejb.SessionContext;
    public class StatelessSampleEJBBean implements SessionBean {
      public void ejbCreate(){}
      public void ejbActivate(){}
      public void ejbPassivate(){}
      public void ejbRemove(){}
      public void setSessionContext(SessionContext ctx){
      public void createDepartment(int id, String name, String loc) 
      throws AppException {
        // TODO: Implement method here
    }We can double-click on the ejb-jar.xml file in our project to see the XML deployment descriptor for the bean we just created:
    <ejb-jar>
       <enterprise-beans>
          <session>
             <description>Session Bean ( Stateless )</description>
             <display-name>StatelessSampleEJB</display-name>
             <ejb-name>StatelessSampleEJB</ejb-name>
             <home>com.example.StatelessSampleEJBHome</home>
             <remote>com.example.StatelessSampleEJB</remote>
             <ejb-class>com.example.StatelessSampleEJBBean</ejb-class>
             <session-type>Stateless</session-type>
             <transaction-type>Container</transaction-type>
          </session>
       </enterprise-beans>
    </ejb-jar>We need to add the extra <assembly-descriptor> section in this file to indicate that the createDepartment method will require a transaction. After this edit, the ejb-jar.xml file looks like this:
    <ejb-jar>
       <enterprise-beans>
          <session>
             <description>Session Bean ( Stateless )</description>
             <display-name>StatelessSampleEJB</display-name>
             <ejb-name>StatelessSampleEJB</ejb-name>
             <home>com.example.StatelessSampleEJBHome</home>
             <remote>com.example.StatelessSampleEJB</remote>
             <ejb-class>com.example.StatelessSampleEJBBean</ejb-class>
             <session-type>Stateless</session-type>
             <transaction-type>Container</transaction-type>
          </session>
       </enterprise-beans>
       <assembly-descriptor>
          <container-transaction>
             <method>
                <ejb-name>StatelessSampleEJB</ejb-name>
                <method-name>createDepartment</method-name>
                <method-params>
                   <method-param>int</method-param>
                   <method-param>java.lang.String</method-param>
                   <method-param>java.lang.String</method-param>
                </method-params>
             </method>
             <trans-attribute>Required</trans-attribute>
          </container-transaction>
       </assembly-descriptor>
    </ejb-jar>
    Aggregating a BC4J Application Module
    With the EJB aspects of our bean setup, we can proceed to implementing the BC4J application module aggregation.
    The first thing we do is add private variables to hold the EJB SessionContext and the instance of the aggregated BC4J ApplicationModule, like this:
    // Place to hold onto the aggregated appmodule instance
    transient private ApplicationModule _am  = null;
    // Remember the SessionContext that the EJB container provides us
    private           SessionContext    _ctx = null;and we modify the default, empty implementation of the setSessionContext() method to remember the session context like this:
    public void setSessionContext(SessionContext ctx){ _ctx = ctx; }We add additional constants that hold the names of the J2EE datasource that we want BC4J to use, as well as the fully-qualified name of the BC4J application module that we'll be aggregating:
    // JNDI resource name for the J2EE datasource to use
    private static final String DATASOURCE = "jdbc/OracleCoreDS";
    // Fully-qualified BC4J application module name to aggregate
    private static final String APPMODNAME = "com.example.hr.HRApp";We expand the now-empty ejbCreate() and ejbRemove() methods to create and destory the aggregated instance of the BC4J application module that we'll use for the lifetime of the stateless session bean. When we're done, ejbCreate() it looks like this:
    public void ejbCreate() throws CreateException {
      try {
        // Setup a hashtable of environment parameters for JNDI initial context
        Hashtable env = new Hashtable();
        env.put(JboContext.INITIAL_CONTEXT_FACTORY,JboContext.JBO_CONTEXT_FACTORY);
        // NOTE: we want to use the BC4J app module in local mode as a simple Java class!
        env.put(JboContext.DEPLOY_PLATFORM, JboContext.PLATFORM_LOCAL);
        env.put(PropertyConstants.INTERNAL_CONNECTION_PARAMS,DATASOURCE);
        // Create an initial context, using this hashtable of environment params
        InitialContext ic = new InitialContext(env);
        // Lookup a home interface for the application module
        ApplicationModuleHome home = (ApplicationModuleHome)ic.lookup(APPMODNAME);
        // Using the home, create the instance of the appmodule we'll use
        _am = home.create();
        // Register the BC4J factory to handle EJB container-managed transactions
        registerContainerManagedTransactionHandlerFactory();
      catch(Exception ex) {
         ex.printStackTrace();
        throw new CreateException(ex.getMessage());
    }and ejbRemove() looks like this:
    public void ejbRemove() {
      try {
        // Cleanup any appmodule resources before getting shutdown
        _am.remove();
      catch(JboException ex) { /* Ignore */ }
    }The helper method named reigsterContainerManagedTransactionHandlerFactory() looks like this:
    private void registerContainerManagedTransactionHandlerFactory() {
      SessionImpl session = (SessionImpl)_am.getSession();
      session.setTransactionHandlerFactory(
        new TransactionHandlerFactory() {
          public TransactionHandler  createTransactionHandler() {
            return new ContainerManagedTxnHandlerImpl();
          public JTATransactionHandler createJTATransactionHandler() {
            return new ContainerManagedTxnHandlerImpl();
    }The last detail is to use the BC4J appmodule to implement the createDepartment() method. It ends up looking like this:
    public void createDepartment(int id, String name, String loc)
    throws AppException {
      try {
        // Connect the AM to the datasource we want to use for the duration
        // of this single method call.
        _am.getTransaction().connectToDataSource(null,DATASOURCE,false);
        // Use the "Departments" view object member of this AM
        ViewObject departments = _am.findViewObject("Departments");
        // Create a new row in this view object.
        Row newDept = departments.createRow();
        // Populate the attributes from the parameter arguments.
        newDept.setAttribute("Deptno", new Number(id));
        newDept.setAttribute("Dname", name);
        newDept.setAttribute("Loc", loc);
        // Add the new row to the view object's default rowset
        departments.insertRow(newDept);
        // Post all changes in the AM, but we don't commit them. The EJB
        // container managed transaction handles the commit.
        _am.getTransaction().postChanges();
      catch(JboException ex) {
        // To be good EJB Container-Managed Transaction "citizens" we have
        // to mark the transaction as needing a rollback if there are problems
        _ctx.setRollbackOnly();
        throw new AppException("Error creating dept "+ id +"\n"+ex.getMessage());
      finally {
        try {
          // Disconnect the AM from the datasource we're using
          _am.getTransaction().disconnect();
        catch(Exception ex) { /* Ignore */ }
    Building a Test Client
    With the EJB-Tier work done, we can build a sample client program to test this new stateless EJB Session Bean by selecting the bean in the Oracle9i JDeveloper IDE and choosing "Create Sample Java Client" from the right-mouse menu.
    When the "Sample EJB Client Details" dialog appears, we take the defaults of connecting to embedded OC4J container. Clicking the (OK) button generates the following test class:
    import java.util.Hashtable;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import com.example.StatelessSampleEJB;
    import com.example.StatelessSampleEJBHome;
    public class SampleStatelessSampleEJBClient {
      public static void main(String [] args) {
        SampleStatelessSampleEJBClient sampleStatelessSampleEJBClient =
           new SampleStatelessSampleEJBClient();
        try {
          Hashtable env = new Hashtable();
          env.put(Context.INITIAL_CONTEXT_FACTORY,
                  "com.evermind.server.rmi.RMIInitialContextFactory");
          env.put(Context.SECURITY_PRINCIPAL, "admin");
          env.put(Context.SECURITY_CREDENTIALS, "welcome");
          env.put(Context.PROVIDER_URL,
                  "ormi://localhost:23891/current-workspace-app");
          Context ctx = new InitialContext(env);
          StatelessSampleEJBHome statelessSampleEJBHome =
               (StatelessSampleEJBHome)ctx.lookup("StatelessSampleEJB");
          StatelessSampleEJB statelessSampleEJB;
          // Use one of the create() methods below to create a new instance
          // statelessSampleEJB = statelessSampleEJBHome.create();
          // Call any of the Remote methods below to access the EJB
          // statelessSampleEJB.createDepartment( int id, java.lang.String name, java.lang.String loc );
        catch(Throwable ex) {
          ex.printStackTrace();
    }We uncomment the call to the create() method and add a few calls to the createDepartment() method so that the body of the test program now looks like this:
    // Use one of the create() methods below to create a new instance
    statelessSampleEJB = statelessSampleEJBHome.create();
    // Call any of the Remote methods below to access the EJB
    statelessSampleEJB.createDepartment( 13, "Test1","Loc1");
    System.out.println("Created department 13");
    statelessSampleEJB.createDepartment( 14, "Test2","Loc2");
    System.out.println("Created department 14");
    try {
      // Try setting a department id that is too large!
      statelessSampleEJB.createDepartment( 23456, "Test3","Loc3");
    catch (AppException ax) {
      System.err.println("AppException: "+ax.getMessage());
    }Before we can successfully run our SampleStatelessSampleEJBClient we need to first run the EJB bean that the client will try to connect to. Since Oracle9i JDeveloper supports local running and debugging of the EJB-Tier without doing through a full J2EE deployment step, to accomplish this prerequisite step we just need to right-mouse on the StatelessSampleEJB node in the System Navigator and select "Run". This starts up the embedded OC4J instance and runs the EJB right out of the current out path.Finally, we can run the SampleStatelessSampleEJBClient, and see the output of the test program in the JDeveloper log window:
    Created department 13
    Created department 14
    AppException: Error creating dept 23456
    JBO-27010: Attribute set with value 23456 for Deptno in Dept has invalid precision/scale
    Troubleshooting
    One error that might arise while running the example is that the database connection information in your data-sources.xml for the jdbc/OracleCoreDS datasource does not correspond to the database you are trying to test against. If this happens, then double-check the file .\jdev\system\oc4j-config\data-sources.xml under the JDeveloper installation home directory to make sure that the url value provided is what you expect. For example, to work against a local Oracle database running on your current machine, listening on port 1521, with SID of ORCL, you would edit this file to have an entry like this for jdbc/OracleCoreDS :
    <data-source
        class="com.evermind.sql.DriverManagerDataSource"
        name="OracleDS"
        location="jdbc/OracleCoreDS"
        xa-location="jdbc/xa/OracleXADS"
        ejb-location="jdbc/OracleDS"
        connection-driver="oracle.jdbc.driver.OracleDriver"
        username="scott"
        password="tiger"
        url="jdbc:oracle:thin:@localhost:1521:ORCL"
        inactivity-timeout="30"
    />This is the data-sources.xml file that gets used by the embedded OC4J instance running in JDeveloper.
    Conclusion
    Hopefully this article has illustrated that it is straightforward to utilize the full power of BC4J in local mode as part of your EJB Stateless Session Beans using container-managed transaction. This example illustrated a single createDepartment method in the enterprise bean, but by replicating the application module interaction code that we've illustrated in createDepartment, any number of methods in your stateless session bean can use the aggregated application module instance created in the ejbCreate() method.
    Code Listing
    The full code listing for the SampleStatelessEJB bean implementation class looks like this:
    * StatelessSampleEJB
    * Illustrates how to use an aggregated BC4J application module
    * in local mode as part of the implementation of a stateless
    * EJB session bean using container-managed transaction.
    * HISTORY
    * smuench/dmutreja 14-FEB-2002 Created
    package com.example;
    import oracle.jbo.*;
    import oracle.jbo.server.*;
    import javax.ejb.*;
    import oracle.jbo.domain.Number;
    import oracle.jbo.common.PropertyConstants;
    import java.util.Hashtable;
    import javax.naming.InitialContext;
    import oracle.jbo.server.ejb.ContainerManagedTxnHandlerImpl;
    public class StatelessSampleEJBBean implements SessionBean {
      // JNDI resource name for the J2EE datasource to use
      private static final String DATASOURCE = "jdbc/OracleCoreDS";
      // Fully-qualified BC4J application module name to aggregate
      private static final String APPMODNAME = "com.example.hr.HRApp";
      // Place to hold onto the aggregated appmodule instance
      transient private ApplicationModule _am  = null;
      // Remember the SessionContext that the EJB container provides us
      private           SessionContext    _ctx = null;
      public void ejbCreate() throws CreateException {
        try {
          // Setup a hashtable of environment parameters for JNDI initial context
          Hashtable env = new Hashtable();
          env.put(JboContext.INITIAL_CONTEXT_FACTORY,JboContext.JBO_CONTEXT_FACTORY);
          env.put(JboContext.DEPLOY_PLATFORM, JboContext.PLATFORM_LOCAL);
          env.put(PropertyConstants.INTERNAL_CONNECTION_PARAMS,DATASOURCE);
          // Create an initial context, using this hashtable of environment params
          InitialContext ic = new InitialContext(env);
          // Lookup a home interface for the application module
          ApplicationModuleHome home = (ApplicationModuleHome)ic.lookup(APPMODNAME);
          // Using the home, create the instance of the appmodule we'll use
          _am = home.create();
          // Register the BC4J factory to handle EJB container-managed transactions
          registerContainerManagedTransactionHandlerFactory();
        catch(Exception ex) {
           ex.printStackTrace();
          throw new CreateException(ex.getMessage());
      public void ejbActivate(){}
      public void ejbPassivate(){}
      public void ejbRemove(){}
      public void setSessionContext(SessionContext ctx){ _ctx = ctx; }
      public void createDepartment(int id, String name, String loc)
      throws AppException {
        try {
          // Connect the AM to the datasource we want to use for the duration
          // of this single method call.
          _am.getTransaction().connectToDataSource(null,DATASOURCE,false);
          // Use the "Departments" view object member of this AM
          ViewObject departments = _am.findViewObject("Departments");
          // Create a new row in this view object.
          Row newDept = departments.createRow();
          // Populate the attributes from the parameter arguments.
          newDept.setAttribute("Deptno", new Number(id));
          newDept.setAttribute("Dname", name);
          newDept.setAttribute("Loc", loc);
          // Add the new row to the view object's default rowset
          departments.insertRow(newDept);
          // Post all changes in the AM, but we don't commit them. The EJB
          // container managed transaction handles the commit.
          _am.getTransaction().postChanges();
        catch(JboException ex) {
          // To be good EJB Container-Managed Transaction "citizens" we have
          // to mark the transaction as needing a rollback if there are problems
          _ctx.setRollbackOnly();
          throw new AppException("Error creating dept "+ id +\n"+ex.getMessage());
        finally {
          try {
            // Disconnect the AM from the datasource we're using
            _am.getTransaction().disconnect();
          catch(Exception ex) { /* Ignore */ }
      private void registerContainerManagedTransactionHandlerFactory() {
        SessionImpl session = (SessionImpl)_am.getSession();
        session.setTransactionHandlerFactory(
          new TransactionHandlerFactory() {
            public TransactionHandler createTransactionHandler() {
              return new ContainerManagedTxnHandlerImpl();
            public JTATransactionHandler createJTATransactionHandler() {
              return new ContainerManagedTxnHandlerImpl();

    Hi Steve, It4s me again;
    About the question I made, I tried with a single assembly-descriptor tag and a single container-transaction tag in the deployment descriptor of the session bean and these were the results.
    java.lang.NullPointerException
         void com.evermind.server.rmi.RMIConnection.EXCEPTION_ORIGINATES_FROM_THE_REMOTE_SERVER(java.lang.Throwable)
         java.lang.Object com.evermind.server.rmi.RMIConnection.invokeMethod(com.evermind.server.rmi.RMIContext, long, long, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.rmi.RemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.rmi.RecoverableRemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.ejb.StatelessSessionRemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         void __Proxy1.modificaEnvoltura(java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.String)
         void SamplemdeController.envolturaControlEJBClient.main(java.lang.String[])
    Then I tried with multiple assembly-descriptor tags each with a single container-transaction tag and the results were:
    java.lang.NullPointerException
         void com.evermind.server.rmi.RMIConnection.EXCEPTION_ORIGINATES_FROM_THE_REMOTE_SERVER(java.lang.Throwable)
         java.lang.Object com.evermind.server.rmi.RMIConnection.invokeMethod(com.evermind.server.rmi.RMIContext, long, long, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.rmi.RemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.rmi.RecoverableRemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.ejb.StatelessSessionRemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         void __Proxy1.modificaEnvoltura(java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.String)
         void SamplemdeController.envolturaControlEJBClient.main(java.lang.String[])
    Finally I tried with a single assembly-descriptor and multiple container tags and the results were:
    java.lang.NullPointerException
         void com.evermind.server.rmi.RMIConnection.EXCEPTION_ORIGINATES_FROM_THE_REMOTE_SERVER(java.lang.Throwable)
         java.lang.Object com.evermind.server.rmi.RMIConnection.invokeMethod(com.evermind.server.rmi.RMIContext, long, long, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.rmi.RemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.rmi.RecoverableRemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.ejb.StatelessSessionRemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         void __Proxy1.modificaEnvoltura(java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.String)
         void SamplemdeController.envolturaControlEJBClient.main(java.lang.String[])
    How can I make my Stateless Session bean work out?

  • How to make a JTree respond to changes in the Hashtable

    Hi,
    Can anyone give the classes and methods from which I can make the JTree reflect to changes in the Hashtable. Im using the hashtable to construct a JTree but changes in hashtable are not reflected to the JTree.
    I used tree.updateUI(). It works if I insert to a collapsed node. In case a node is expanded and if I add a node to it through the Hashtable it does not reflect.
    Thanking u,
    Karan.

    A JTree will reflect changes made to its model if this model does fire the appropriate events. So, make sure to update the tree's model whenever necessary. See also [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html].

  • Performance using Generic Sync

    Hey Guys,
    i am facing a problem. Syncronization using MI installed on my laptop takes 3667 ms, but starting a sync from my pda takes 95425 seconds.
    it is only the time sm.synchronizeWithBackend(); needs until the inboundprocesshandler starts working.
    i am using windows mobile 5 and 6 and the connection is made using a usb cable and active sync
    what can i do. the sync transfers only very little data, just some strings to get information about a workarea.
    Philipp

    Hi Philipp,
      Sync from PDA will definitely take more time (3 to 4 times depends on data) than one a laptop. You can't compare both as the processing power & memory of a PDA is too inferior compared to laptop.
    For your problem, Check that this is not an isolated incident. Do test multiple times (min 3) and try to get a common time.  Also do a statistical record check (Tcode: STAD) in the Middleware server for both laptop and client syncs and see the timings are the same.
    Enable trace level to ALL in the PDA and check the trace for any errors. Also that will give you the time for downloading the data and persisting the data.
    Regards
    Ajith Chandran

Maybe you are looking for

  • MacBook Pro 2011 won't turn on

    Hey I'm hoping someone can help me before I'm forced to bring it in. My computer froze while playing San Andreas so I manually turned it off. Now when I go to turn it on nothing happens. The battery indicator flashes the first led for five seconds bu

  • Symbol does not clone properly

    I clone a symbol (button) and change its rollover color, but the other symbols (from wich this one was cloned) get updated... I need the new symbol to have unique rollover. This is Firesworks CS3 Thanx!.

  • Downloaded messages will not show in inbox.

    I'm using a BlackBerry 8900, though that's obvious I suppose, on a BES server at a University.  We recently shifted everyone at the U to a new server and now although I have notifications that there are 32000+ messages in my inbox, I can't see any of

  • OS X 10.5 and displaying network passwords...

    I knew with Tiger there was a way to display my 128 bit WEP password so that I can allow peripheral components (read:xbox) onto the network. Did they take that away in Leopard? Is there another way? Help!

  • Composite Input Driver Problems

    Okay< so I have a HP Media Center PC m7060n and on the front, it has an input for composite (yellow, red, and white) and everytime I connect my Wii there..I go to WinDVD Creator to see the display..but then..under devices..composite input is not ther