Best Practice to Atomic Read and Write a Field In Database

I am from Java Desktop Application background. May I know what is the best practice in J2EE, to atomic read and write a field in database. Currently, here is what I did
// In Servlet.
synchronized(private_static_final_object)
    int counter = read_counter_from_database();
    counter++;
    write_counter_back_to_database(counter);
}However, I suspect the above method will work all the time.
As my observation is that, if I have several web request at the same time, I am executing code within single instance of servlet, using different thread. The above method shall work, as different thread web request, are all referring to same "private_static_final_object"
However, my guess is "single instance of servlet" is not guarantee. As after some time span, the previous instance of servlet may destroy, with another new instance of servlet being created.
I also came across [http://code.google.com/appengine/docs/java/datastore/transactions.html|http://code.google.com/appengine/docs/java/datastore/transactions.html] in JDO. I am not sure whether they are going to solve the problem.
// In Servlet.
Transaction tx = pm.currentTransaction();
tx.begin();
    int counter = read_counter_from_database();  // Line 1
    counter++;                                                  // Line 2
    write_counter_back_to_database(counter);    // Line 3
tx.commit();Is the code guarantee only when Thread A finish execute Line 1 till Line 3 atomically, only Thread B can continue to execute Line 1 till Line 3 atomically?
As I do not wish the following situation happen.
(1) Thread A read counter from Database as 0
(2) Thread A increment counter to 1
(3) Thread B read counter from Database as 0
(4) Thread A write counter as 1 to database
(5) Thread B increment counter to 1
(6) Thread B write counter as 1 to database
What I wish is
(1) Thread A read counter from Database as 0
(2) Thread A increment counter to 1
(4) Thread A write counter as 1 to database
(3) Thread B read counter from Database as 1
(5) Thread B increment counter to 2
(6) Thread B write counter as 2 to database
Thanks you.
Edited by: yccheok on Oct 27, 2009 8:39 PM

This is my understanding of the issue (you should research it further on you own to get a better understanding):
I suggest you use local variables (ie, defined within a function), and keep away from static variables. Those local variables are thread safe. If you call functions within functions, its still thread safe. If you read or write to one record in a database using sql, its thread safe (you dont need a transaction). If you read/write to multiple tables and/or records, you probably need a transaction. Servlets are thread safe. You usually dont need the 'synchronized' word anywhere unless you have a function updating/reading a static variable and therefore want to ensure only one user is accessing the static varible at a time. Also do so if you are writing to some resource (such as a file, a variable in applicaton scope, session scope, or resource that everyone uses such as email server). You dont want more than one person at a time to write to it). Note the database is one of of those resources that is handled by transactions rather than the the synchronized keyword (the synchronized keyword is applied to your application only (not other applications that someone is running), whereas the transaction ensures all applications are locked out while you update those records in the database).
By the way, if you have a static variable, you should have one and only one function (synchronized) that updates it that everyone uses. If you have more than one synchronized function, that updates it, its probably not thread safe.
An example of a static variable you would use is a Datasource object (to obtain your database connections). You only need one connection pool in your application and you access it via the datasource variable.
If you're unsure your code is thread safe, you can create two seperate threads that call the same block of functions repeatedly to ensure it works as expected.

Similar Messages

  • Atomic reads and writes to memory

    In Solaris 10 running on x86 64bit processor are reads/writes of an int variable (written in C compiled with gcc) atomic operations? I have read on various forums that memory reads and writes of primitives are atomic but there are people who question this statement.
    I know there are atomic_ops provided by Solaris 10 for both user space and kernel but I am only interested in ensuring that an update to an int is atomic?

    ps10x# cat fred.c
    main() {
      int i;
      i=13;
      i=17;
    ps10x# gcc -S fred.c
    ps10x# cat fred.s
            .file   "fred.c"
            .text
    .globl main
            .type   main, @function
    main:
            leal    4(%esp), %ecx
            andl    $-16, %esp
            pushl   -4(%ecx)
            pushl   %ebp
            movl    %esp, %ebp
            pushl   %ecx
            subl    $20, %esp
            movl    $13, -8(%ebp)
            movl    $17, -8(%ebp)
            addl    $20, %esp
            popl    %ecx
            popl    %ebp
            leal    -4(%ecx), %esp
            ret
            .size   main, .-main
            .ident  "GCC: (GNU) 4.3.4"So it seems pretty clear that setting a variable is "movl $13, -8(%ebp)"
    and while I'm no expert on x86 assembler, I'm fairly sure a single movl instruction is atomic.
    However, the real issue is that the compiler might decide to stash a temporary copy of the variable in a register.
    And that could throw off the "atomic" nature of things.
    I believe that the volatile keyword is supposed to help prevent those kinds of issues.

  • Reading and writing to a MySQL database with Java

    Anyone knows what's the best way to read and write from a MySQL database?

    > Anyone knows what's the best way to read and write
    from a MySQL database?
    Yep!
    The Java� Tutorial - Trail: JDBC� Database Access
    MySQL Reference Manual
    MySQL Connector/J Documentation
    Driver/Datasource Class Names, URL Syntax and Configuration Properties for Connector/J
    Best of luck!
    ~

  • What is the best combination of read and write objects to binary files ...

    Hi everyone,
    what are the best combination of read and write objects to read/write a record of customers from a binary file. I should be able to use StringTokenizer. I am bit confused with all these Stream reader and writers.
    abdul

    You are, indeed, confused:
    o StreamTokenizer works on character input, not binary input.
    o Readers and Writers in general work on character streams, not binary.
    That leaves you various input streams and output streams for reading binary data.

  • Why does this class not read and write at same time???

    I had another thread where i was trying to combine two class files together
    http://forum.java.sun.com/thread.jspa?threadID=5146796
    I managed to do it myself but when i run the file it does not work right. If i write a file then try and open the file it says there are no records in the file, but if i close the gui down and open the file everything get read in as normal can anybody tell me why?
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import bank.BankUI;
    import bank.*;
    public class testing extends JFrame {
       private ObjectOutputStream output;
       private BankUI userInterface;
       private JButton SaveToFile, SaveAs, Exit; //////////savetofile also saves to store need to split up and have 2 buttons
       //private Store store; MIGHT BE SOMETHING TO DO WITH THIS AS I HAD TO COMMENT THIS STORE OUT TO GET IT WORKING AS STORE IS USED BELOW
       private Employee record;
    //////////////////////////////////////from read
    private ObjectInputStream input;
       private JButton nextButton, openButton, nextRecordButton ;
       private Store store = new Store(100);
         private Employee employeeList[] = new Employee[100];
         private int count = 0, next = 0;
    /////////////////////////////////////////////from read end
       // set up GUI
       public testing()
          super( "Employee Data" ); // appears in top of gui
          // create instance of reusable user interface
          userInterface = new BankUI( 9 );  // nine textfields
          getContentPane().add( userInterface, BorderLayout.CENTER );
          // configure button doTask1 for use in this program
          SaveAs = userInterface.getSaveAsButton();
          SaveAs.setText( "Save as.." );
    //////////////////from read
    openButton = userInterface.getOpenFileButton();
          openButton.setText( "Open File" );
    openButton.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // close file and terminate application
                public void actionPerformed( ActionEvent event )
                   openFile();
             } // end anonymous inner class
          ); // end call to addActionListener
          // register window listener for window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // close file and terminate application
                public void windowClosing( WindowEvent event )
                   if ( input != null )
                             closeFile();
                   System.exit( 0 );
             } // end anonymous inner class
          ); // end call to addWindowListener
          // get reference to generic task button doTask2 from BankUI
          nextButton = userInterface.getDoTask2Button();
          nextButton.setText( "Next Record" );
          nextButton.setEnabled( false );
          // register listener to call readRecord when button pressed
          nextButton.addActionListener(
             // anonymous inner class to handle nextRecord event
             new ActionListener() {
                // call readRecord when user clicks nextRecord
                public void actionPerformed( ActionEvent event )
                   readRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
    //get reference to generic task button do Task3 from BankUI
          // get reference to generic task button doTask3 from BankUI
          nextRecordButton = userInterface.getDoTask3Button();
          nextRecordButton.setText( "Get Next Record" );
          nextRecordButton.setEnabled( false );
          // register listener to call readRecord when button pressed
          nextRecordButton.addActionListener(
             // anonymous inner class to handle nextRecord event
             new ActionListener() {
                // call readRecord when user clicks nextRecord
                public void actionPerformed( ActionEvent event )
                   getNextRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
    ///////////from read end
          // register listener to call openFile when button pressed
          SaveAs.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // call openFile when button pressed
                public void actionPerformed( ActionEvent event )
                   SaveLocation();
             } // end anonymous inner class
          ); // end call to addActionListener
          // configure button doTask2 for use in this program
          SaveToFile = userInterface.getSaveStoreToFileButton();
          SaveToFile.setText( "Save to store and to file need to split this task up" );
          SaveToFile.setEnabled( false );  // disable button
          // register listener to call addRecord when button pressed
          SaveToFile.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // call addRecord when button pressed
                public void actionPerformed( ActionEvent event )
                   addRecord(); // NEED TO SPLIT UP SO DONT DO BOTH
             } // end anonymous inner class
          ); // end call to addActionListener
    Exit = userInterface.getExitAndSaveButton();
          Exit.setText( "Exit " );
          Exit.setEnabled( false );  // disable button
          // register listener to call addRecord when button pressed
          Exit.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // call addRecord when button pressed
                public void actionPerformed( ActionEvent event )
                   addRecord(); // adds record to to file
                   closeFile(); // closes everything
             } // end anonymous inner class
          ); // end call to addActionListener
          // register window listener to handle window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // add current record in GUI to file, then close file
                public void windowClosing( WindowEvent event )
                             if ( output != null )
                                addRecord();
                                  closeFile();
             } // end anonymous inner class
          ); // end call to addWindowListener
          setSize( 600, 500 );
          setVisible( true );
         store = new Store(100);
       } // end CreateSequentialFile constructor
       // allow user to specify file name
    ////////////////from read
      // enable user to select file to open
       private void openFile()
          // display file dialog so user can select file to open
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
          int result = fileChooser.showOpenDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          // obtain selected file
          File fileName = fileChooser.getSelectedFile();
          // display error if file name invalid
          if ( fileName == null || fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this, "Invalid File Name",
                "Invalid File Name", JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                input = new ObjectInputStream(
                   new FileInputStream( fileName ) );
                openButton.setEnabled( false );
                nextButton.setEnabled( true );
             // process exceptions opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this, "Error Opening File",
                   "Error", JOptionPane.ERROR_MESSAGE );
          } // end else
       } // end method openFile
    public void readRecord() // need to merger with next record
          Employee record;
          // input the values from the file
          try {
         record = ( Employee ) input.readObject();
                   employeeList[count++]= record;
                   store.add(record);/////////ADDS record to Store
              store.displayAll();
              System.out.println("Count is " + store.getCount());
             // create array of Strings to display in GUI
             String values[] = {
                        String.valueOf(record.getName()),
                            String.valueOf(record.getGender()),
                        String.valueOf( record.getDateOfBirth()),
                        String.valueOf( record.getID()),
                             String.valueOf( record.getStartDate()),
                        String.valueOf( record.getSalary()),
                        String.valueOf( record.getAddress()),
                           String.valueOf( record.getNatInsNo()),
                        String.valueOf( record.getPhone())
    // i added all those bits above split onto one line to look neater
             // display record contents
             userInterface.setFieldValues( values );
          // display message when end-of-file reached
          catch ( EOFException endOfFileException ) {
             nextButton.setEnabled( false );
          nextRecordButton.setEnabled( true );
             JOptionPane.showMessageDialog( this, "No more records in file",
                "End of File", JOptionPane.ERROR_MESSAGE );
          // display error message if class is not found
          catch ( ClassNotFoundException classNotFoundException ) {
             JOptionPane.showMessageDialog( this, "Unable to create object",
                "Class Not Found", JOptionPane.ERROR_MESSAGE );
          // display error message if cannot read due to problem with file
          catch ( IOException ioException ) {
             JOptionPane.showMessageDialog( this,
                "Error during read from file",
                "Read Error", JOptionPane.ERROR_MESSAGE );
       } // end method readRecord
       private void getNextRecord()
               Employee record = employeeList[next++%count];//cycles throught accounts
          //create aray of string to display in GUI
          String values[] = {String.valueOf(record.getName()),
             String.valueOf(record.getGender()),
              String.valueOf( record.getStartDate() ), String.valueOf( record.getAddress()),
         String.valueOf( record.getNatInsNo()),
         String.valueOf( record.getPhone()),
             String.valueOf( record.getID() ),
               String.valueOf( record.getDateOfBirth() ),
         String.valueOf( record.getSalary() ) };
         //display record contents
         userInterface.setFieldValues(values);
         //display record content
    ///////////////////////////////////from read end
    private void SaveLocation()
          // display file dialog, so user can choose file to open
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
          int result = fileChooser.showSaveDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          File fileName = fileChooser.getSelectedFile(); // get selected file
          // display error if invalid
          if ( fileName == null || fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this, "Invalid File Name",
                "Invalid File Name", JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                output = new ObjectOutputStream(
                   new FileOutputStream( fileName ) );
                SaveAs.setEnabled( false );
                SaveToFile.setEnabled( true );
              Exit.setEnabled( true );
             // process exceptions from opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this, "Error Opening File",
                   "Error", JOptionPane.ERROR_MESSAGE );
          } // end else
       } // end method openFile
       // close file and terminate application
    private void closeFile()
          // close file
          try {
              //you want to cycle through each recordand add them to store here.
                                            int storeSize = store.getCount();
                                            for (int i = 0; i<storeSize;i++)
                                            output.writeObject(store.elementAt(i));
             output.close();
    input.close();// from read!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
             System.exit( 0 );
          // process exceptions from closing file
          catch( IOException ioException ) {
             JOptionPane.showMessageDialog( this, "Error closing file",
                "Error", JOptionPane.ERROR_MESSAGE );
             System.exit( 1 );
       } // end method closeFile
       // add record to file
       public void addRecord()
          int employeeNumber = 0;
          String fieldValues[] = userInterface.getFieldValues();
          // if account field value is not empty
          if ( ! fieldValues[ BankUI.IDNUMBER ].equals( "" ) ) {
             // output values to file
             try {
                employeeNumber = Integer.parseInt(
                   fieldValues[ BankUI.IDNUMBER ] );
                        String dob = fieldValues[ BankUI.DOB ];
                        String[] dateofBirth = dob.split ("-"); // what used to put between number chnage to /
                        String sDate = fieldValues[ BankUI.START ];
                        String[] startDate = sDate.split ("-");
                        String sex = fieldValues[ BankUI.GENDER ];
                        char gender = (sex.charAt(0)); // check if m or f prob check in employee
    if ( employeeNumber >= 0 ) {
                  /* create new record =String name, char gender, Date dob, String add, String nin, String phone, String id, Date start, float salary*/
                    record  = new Employee(
                    fieldValues[ BankUI.NAME ],
                        gender,
                    new Date(     Integer.parseInt(dateofBirth[0]),
                              Integer.parseInt(dateofBirth[1]),
                              Integer.parseInt(dateofBirth[2])),
                        fieldValues[ BankUI.ADDRESS ],
                        fieldValues[ BankUI.NATINTNO ],
                        fieldValues[ BankUI.PHONE ],
                        fieldValues[ BankUI.IDNUMBER ],
              new Date(     Integer.parseInt(startDate[0]),
                              Integer.parseInt(startDate[1]),
                              Integer.parseInt(startDate[2])),
              Float.parseFloat( fieldValues[ BankUI.SALARY ] ));
                        if (!store.isFull())
                             store.add(record);
                        else
                        JOptionPane.showMessageDialog( this, "The Store is full you cannot add\n"+
                         "anymore employees. \nPlease Save Current File and Create a New File." );
                             System.out.println("Store full");
                        store.displayAll();
                        System.out.println("Count is " + store.getCount());
                                  // output record and flush buffer
                                  //output.writeObject( record );
                   output.flush();
                else
                    JOptionPane.showMessageDialog( this,
                       "Account number must be greater than 0",
                       "Bad account number", JOptionPane.ERROR_MESSAGE );
                // clear textfields
                userInterface.clearFields();
             } // end try
             // process invalid account number or balance format
             catch ( NumberFormatException formatException ) {
                JOptionPane.showMessageDialog( this,
                   "Bad ID number, Date or Salary", "Invalid Number Format",
                   JOptionPane.ERROR_MESSAGE );
             // process exceptions from file output
             catch ( ArrayIndexOutOfBoundsException ArrayException ) {
                 JOptionPane.showMessageDialog( this, "Error with Start Date or Date of Birth\nPlease enter like: 01-01-2001",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                      // process exceptions from file output
             catch ( IOException ioException ) {
                 JOptionPane.showMessageDialog( this, "Error writing to file",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                closeFile();
          } // end if
       } // end method addRecord
       public static void main( String args[] )
          new testing();
    } // end class CreateSequentialFile

    Sure you can read and write at the same time. But normally you would be reading from one place and writing to another place.
    I rather regret avoiding the OP's earlier post asking how to combine two classes. I looked at the two classes posted and realized the best thing to do was actually to break them into more classes. But I also realized it was going to be a big job explaining why and how, and I just don't have the patience for that sort of thing.
    So now we have a Big Ball Of Tar&trade; and I feel partly responsible.

  • I have the latest Mac Air 13" and I have a Seagate 500MB external hard disk I cant copy or Cut any files on the hard disk and I cant even delete any files. I have the settings as Read and Write in the get info tab. Please help

    I have the latest Mac Air 13" and I have a Seagate 500MB external hard disk I cant copy or Cut any files on the hard disk and I cant even delete any files. I have the settings as Read and Write in the get info tab. Please helpand also note that my hard drive was formatted on a Windows 7 Laptop.

    thats the problem, its in MSDos (Fat) or NTFS for Windows.
    Options.....
    1. offload all that data on the HD onto your PC, THEN format the HD in EXFAT for use on BOTH PC and Mac for read/write.....then reload all (or as you need) that data back onto the HD
    2. get another HD, and format it for Mac OSX extended journaled.
    FAT32 (File Allocation Table)
    Read/Write FAT32 from both native Windows and native Mac OS X.
    Maximum file size: 4GB.
    Maximum volume size: 2TB
    You can use this format if you share the drive between Mac OS X and Windows computers and have no files larger than 4GB.
    NTFS (Windows NT File System)
    Read/Write NTFS from native Windows.
    Read only NTFS from native Mac OS X
    To Read/Write/Format NTFS from Mac OS X, here are some alternatives:
    For Mac OS X 10.4 or later (32 or 64-bit), install Paragon (approx $20) (Best Choice for Lion)
    Native NTFS support can be enabled in Snow Leopard and Lion, but is not advisable, due to instability.
    AirPort Extreme (802.11n) and Time Capsule do not support NTFS
    Maximum file size: 16 TB
    Maximum volume size: 256TB
    You can use this format if you routinely share a drive with multiple Windows systems.
    HFS+     ((((MAC FORMAT)))  (Hierarchical File System, a.k.a. Mac OS Extended (Journaled) Don't use case-sensitive)
    Read/Write HFS+ from native Mac OS X
    Required for Time Machine or Carbon Copy Cloner or SuperDuper! backups of Mac internal hard drive.
    To Read HFS+ (but not Write) from Windows, Install HFSExplorer
    Maximum file size: 8EiB
    Maximum volume size: 8EiB
    You can use this format if you only use the drive with Mac OS X, or use it for backups of your Mac OS X internal drive, or if you only share it with one Windows PC (with MacDrive installed on the PC)
    EXFAT (FAT64)    ------Can read/write from both PC and Mac
    Supported in Mac OS X only in 10.6.5 or later.
    Not all Windows versions support exFAT. 
    exFAT (Extended File Allocation Table)
    AirPort Extreme (802.11n) and Time Capsule do not support exFAT
    Maximum file size: 16 EiB
    Maximum volume size: 64 ZiB
    You can use this format if it is supported by all computers with which you intend to share the drive.  See "disadvantages" for details.

  • Windows 2008 R2 Folder assign permission "Read and Write" problem with *.doc file

    Hello All,
    I am a new one here,
    I am sorry for any mistakes and also my english is so poor.
    M Brother company runing Windows 2008 R2 as Active Directory...
    We have folder Name: Admin
    and in this folder, there are alot documents files as : *.doc, *.dwg, *.txt etc.....
    All user accesing to these files and they can open to edit and save...
    One day my brother want me to set Admin folder for all users just"Read and Write.." mean they still can open files to edit and save... but can't delete..
    I did success with this..
    But only one thing happen.. when they open *.doc file to edit and attempting to save, the message alert" access denide " and they can only "SAVE AS"...We don't want "Save as"
    Could you show me how can we fix error with *.doc file while they trying to save? because it allow only save as.. but other files as *.text file or *.dwg they can save without problem..
    Could expert here ever face this issues and fix by yourself, please share me with this..
    Please help me..
    Best regards,

    Hi,
    Office programs are specific. They will create a temp file when edit, then the temp file will be deleted when close. So Delete permission is needed for users to saving Office files like Excel/Word.
    For more detaile information, please refer to the thread below:
    Special Permissions - User cannot save files
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/721fb2f1-205b-46e5-a3dc-3029e5df9b5b/special-permissions-user-cannot-save-files
    Best Regards,
    Mandy 
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected]

  • Read and Write data in iphone app

    I want to build a simple offline mobile app which reads and writes or stores info to a file, xml, json, txt or whatever.
    What is the best way to do this?
    I am currently learing jQuery and PHP, so I don't want to have to learn some other million things that does one thing but not another.
    Can this be achived without objective C? Can i do this with Jquery and phone Gap?
    Thanks

    Do a search for 'HTML 5 Storage' and you'll find a bunch of resources that will help. Here's a few
    http://www.w3schools.com/HTML/html5_webstorage.asp
    http://diveintohtml5.info/storage.html
    http://htmlpad.wordpress.com/2010/03/10/html-5-data-storage-javascript-api-on-ipad-and-iph one/

  • How to read and write Unicode text with MS Access?

    Hi all, I'm new to Java, so please forgive me if my question is too ... ^_^
    I'm writing a small program that read and write data with MS Access. However, when I insert Unicode text into the database, it has wrong encoding like this "h?y l? n?m".
    Please tell me how to fix this.
    Thanks in advance!

    The following forum thread might be enlightening:
    http://forum.java.sun.com/thread.jspa?threadID=573855&messageID=2870785
    I myself do not use MS Access, but a PreparedStatement is in general the best option.
    You can set parameters in the SQL which then get converted and even protected against SQL injection hacking.

  • Idoc processing best practices - use of RBDAPP01 and RBDMANI2

    We are having performance problems in the processing of inbound idocs.  The message type is SHPCON, and transaction volume is very high.  I am a functional consultant, not an ABAP developer, but will try my best to explain our current setup.
    1)     We have a number of message variants for the inbound SHPCON message, almost all of which are set to trigger immediately upon receipt under the Processing by Function Module setting.
    2)      For messages that fail to process on the first try, we have a batch job running frequently using RBDMANI2.
    We are having some instances of the RBDMANI2 almost every day which get stuck running for a very long period of time.  We frequently have multiple SHPCON idocs coming in containing the same material number, and frequently have idocs fail because the material in the idoc has become locked.  Once the stuck batch job is cancelled and the job starts running again normally, the materials unlock and the failed idocs begin processing.  The variant for the RBDMANI2 batch job is currently set with a packet size of 1 and without parallel processing enabled.
    I am trying to determine the best practice for processing inbound idocs such as this for maximum performance in a very high volume system.  I know that RBDAPP01 processes idocs in status 64 and 66, and RBDMANI2 is used to reprocess idocs in all statuses.  I have been told that setting the messages to trigger immediately in WE20 can result in poor performance.  So I am wondering if the best practice is to:
    1)     Set messages in WE20 to Trigger by background program
    2)     Have a batch job running RBDAPP01 to process inbound idocs waiting in status 64
    3)     Have a periodic batch job running RBDMANI2 to try and clean up any failed messages that can be processed
    I would be grateful if somebody more knowledgeable than myself on this can confirm the best practice for this process and comment on the correct packet size in the program variant and whether or not parallel processing is desirable.  Because of the material locking issue, I felt that parallel processing was not desirable and may actually increase the material locking problem.  I would welcome any comments.
    This appeared to be the correct area for this discussion based upon other discussions.  If this is not the correct area for this discussion, then I would be grateful if the moderator could re-assign this discussion to the correct area (if possible) or let me know the best place to post it.  Thank you for your help.

    Hi Bob,
    Not sure if there is an official best practice, but the note 1333417 - Performance problems when processing IDocs immediately does state that for the high volume the immediate processing is not a good option.
    I'm hoping that for SHPCON there is no dependency in the IDoc processing (i.e. it's not important if they're processed in the same sequence or not), otherwise it'd add another complexity level.
    In the past for the high volume IDoc processing we scheduled a background job with RBDAPP01 (with parallel processing) and RBDMANIN as a second step in the same job to re-process the IDocs with errors due to locking issues. RBDMANI2 has a parallel processing option, but it was not needed in our case (actually we specifically wouldn't want to parallel-process the errors to avoid running into a lock issue again). In short, your steps 1-3 are correct but 2 and 3 should rather be in the same job.
    Also I believe we had a designated server for the background jobs, which helped with the resource availability.
    As a side note, you might want to confirm that the performance issues are caused only by the high volume. An ABAPer or a Basis admin should be able to run a performance trace. There might be an inefficiency in the process that could be adding to the performance issue as well.
    Hope this helps.

  • MMO best practice. Download music and heavy files to users hard disk?

    MMO best practice. Download music and heavy files to users hard disk?
    I have just downloaded a Hello Kitty MMO app for research (for my kid of course).
    I am developping my English teaching app with LOADS of classical music, mp3 sentences and heavy background bgs. Would the best idea be for client to download these to their hardisk ie I would not need to stream them and therefore save a fortune on bandwidth charges from my ISP???
    Cheers

    I see what you mean ie: they have to get the file to their computer one way or another BUT
    a. If they are going to repeatedly use that file ie: a custom cursor or classical piece of music every week when they log on then it would be better for them to have it on their hardisk wouldn't it? If not, they would have to download it every time they log on. I take it that's why the hello kitty site makes you download 130 megas so you have everything on your hardisk, ie: you will be reusing all those assets MANY times in the future. The experience wil be very FAST as you have it on your local disk and needn't have to wait for streaming.

  • Read and write existing xml file trouble !

    Hi everyone ! 
    i'm trying to save hight score of user in my game by using a xml file , in my xml file has element <best_score>0<best_score/>
    and my code to do it is : 
     XElement best=XElement.Load("Assets/best.xml");
                IEnumerable<XElement> loc = best.Elements("best_score");
                foreach (XElement elem in loc)
                    int check=Convert.ToInt32(elem.Value.ToString());
                    int score_user = Convert.ToInt32(scores.ToString());
                    if (score_user >= check)
                       hight_score.Text = score.ToString();
                         elem.Value = scores.ToString();
                         // what code to save this  xml file  after modify ?????
                    else
                        list_box.Text = check.ToString();
    i down know what method can help me save my xml file after update hight score of user in this case .  
    Anyone has an idea to solve it for me ? please , thanks you ! 
    sorry about my english ! 

    Hi,
    It is not recommended to update a file withing the project, so you need to store it in the IsolatedStorage.
    Here is a sample to read and write file in IsolatedStorage,
    XDocument xDoc;
    var file = Util.ReadFile("XMLFile.xml");
    if (file != null)
    xDoc = XDocument.Parse(file);
    var bestScore = xDoc.Element("best_score").Value;
    //do calculation
    xDoc.Element("best_score").Value = "200";
    Util.SaveFile("XMLFile.xml", xDoc.ToString());
    For the above code to work, you need to have a file named "XMLFile.xml" in your IsolatedStorage, with data as  "<best_scrore>200</best_scrore>"
    To read and write file:
    public static class Util
    public static void SaveFile(string filename, string data)
    try
    using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
    using (var stream = new IsolatedStorageFileStream(filename, FileMode.Create, FileAccess.ReadWrite, store))
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(data);
    writer.Close();
    catch (Exception)
    Debug.WriteLine("Couldn't save the file.");
    public static string ReadFile(string filename)
    try
    String data;
    if (!IsolatedStorageFile.GetUserStoreForApplication().FileExists(filename)) return null;
    using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
    using (var stream = new IsolatedStorageFileStream(filename, FileMode.Open, FileAccess.ReadWrite, store))
    StreamReader stmReader = new StreamReader(stream);
    data = stmReader.ReadToEnd();
    stmReader.Close();
    return data;
    catch (Exception)
    return null;
    Pradeep AJ

  • Urgent: Please help. how to solve the time delay during buffer read and write using vc++

    I need to continuously acquire data from daqmx card, write into a file and at the same time corelate (in terms of time) the data with signals from other instruments. The current problem is that there is time delay during read and write data into buffer,thus causing misalignment of the data from multiple instruments. Is there a way to solve  the delay? or Is there a way to mark the time of the data acquisition in the buffer?  If I know the starting time (e.g. 0) of data acquisition and sampling rate (e.g. 1kHz), can I simply add 1ms to each data sample in the buffer? The current code is shown below.
    void DataCollectionWin::ConnectDAQ()
    DAQmxErrChk(DAQmxCreateTask ("", &taskHandle));
        DAQmxErrChk(DAQmxCreateAIVoltageChan(taskHandle,"Dev1/ai0,Dev1/ai1,Dev1/ai2,Dev1/ai3,Dev1/ai4,Dev1/ai5,Dev1/ai16,Dev1/ai17,Dev1/ai18,Dev1/ai19,Dev1/ai20,Dev1/ai21,Dev1/ai6,Dev1/ai7,Dev1/ai22","",DAQmx_Val_Cfg_Default,-10.0,10.0,DAQmx_Val_Volts,NULL));
      DAQmxErrChk(DAQmxCfgSampClkTiming(taskHandle,"",1000.0,DAQmx_Val_Rising,DAQmx_Val_ContSamps,60000));
      DAQmxErrChk (DAQmxRegisterEveryNSamplesEvent(taskHandle,DAQmx_Val_Acquired_Into_Buffer,50,0,EveryNCallback,NULL));// Every 50 samples the EveryNSamplesEvent will be trigured, to reduce time delay.
      DAQmxErrChk (DAQmxRegisterDoneEvent(taskHandle,0,DoneCallback,NULL));
      DAQmxErrChk (DAQmxStartTask(taskHandle));
    int32 CVICALLBACK EveryNCallback(TaskHandle taskHandle, int32 everyNsamplesEventType, uInt32 nSamples, void *callbackData)
     DAQmxErrChk (DAQmxReadAnalogF64(taskHandle,50,10.0,DAQmx_Val_GroupByScanNumber,data,50*15,&read,NULL));
       //memcpy(l_data,data,6000);
      SetEvent(hEvent);
    l_usstatus_e[0]=g_usstatus[0];// signals from other instruments that need to be corelated with the data from daq cards.
     l_optstatus_e[0]=g_optstatus[0];
     if( read>0 ) // write data into file
       //indicator=1;
     for (i=0;i<read;i++)
     {  //fprintf(datafile,"%d\t",i);
      fprintf(datafile,"%c\t",l_usstatus_s[0]);
      fprintf(datafile,"%c\t",l_usstatus_e[0]);
            fprintf(datafile,"%c\t",l_optstatus_s[0]);
      fprintf(datafile,"%c\t",l_optstatus_e[0]);
              fprintf(datafile,"%.2f\t",data[15*i]);
     //   sprintf( pszTemp, "%f", data[6*i]);
     // pListCtrl->SetItemText(0, 2, pszTemp);
        //pWnd->m_trackinglist.SetItemText(0, 2, pszTemp);
         fprintf(datafile,"%.2f\t",data[15*i+1]);
         fprintf(datafile,"%.2f\t",data[15*i+2]);

    Hello kgy,
    It is a bit of a judgment call. You should just choose the board that you think has the most to do with your issue. For example, this issue was much more focused on setting up your data acquisition task than the Measurement Studio environment/tools, so the MultifunctionDAQ board would have been the best place for it. As for moving your post to another board, I do not believe that is possible.
    Regards,
    Dan King

  • Problem with air read and write smb shared directory of file

    hi, everyone.
    I'm want to access smb directory of file,And to read and
    write operation, I would like to ask how I should do?
    Thanks!

    You can't access any OS facility nor execute arbitrary command.
    So the best solution is to mount samba directory BEFORE run your AIR application; you eventually can create a script that mount samba (and asks password) and then run you AIR application.
    see
    http://www.mikechambers.com/blog/2008/01/17/commandproxy-net-air-integration-proof-of-conc ept/
    for a more complex solution.

  • In iCal and Notifications on a notebook, is it possible to expand the notes window to make it easier to read and write notes?

    In iCal and Notifications on a notebook, is it possible to expand the notes window to make it easier to read and write notes? In the past, I have used Outlook calendar and tasks and I was able to expand the windows which allowed me to put a great amount of details into either the notes section in events and tasks. It would be great to be able to do this in iCal and Notifications as well. I am using a Macbook Pro with OS X 10.8. Thank you very much for assistance with this.

    HI,
    Try Spaces for a virtual desktop.
    http://www.ehow.com/how2189851use-spaces-mac-os-x.html
    Carolyn

Maybe you are looking for

  • XFCE - Shutdown and Reboot buttons greyed-out (SOLVED)

    This issue cropped up for me a couple of weeks ago.  Just sat down to try and find a solution.  Followed several suggestions from several posts to no avail. Finally discovered that the syntax for achieving this in "/etc/sudoers" has evidently changed

  • Adding a Photo Gallery to website

    Does anybody know of any good, free, photo galleries that can be embedded/added to a website in Adobe Contribute CS3?

  • IPod Nano 7th Gen Charging Issues

    Over the past two days my nano charges to around 90-95% and then refuses to charge any further, also tried to connect to various usb chargers and computer usb ports. If anyone knows a solution to this its would greatly appreciated.

  • Problems viewing photos and videos

    Hi I have just got my Z1 compact and noticed that when I open camera and select to the pictures (little box bottom right of camera gui) if the phone is in the normal upright position the selection panel (panel where you select which application you w

  • Query the data between two tables

    Need help for query the data between two tables Table 1: Time sheet P.ID      P.Name EmpID HoursSpend DateTime c12234  Test      25        4                06/12/2013 c12234  Test      25        7                06/13/2013 c12234  Test      25