Protecting records in database, multithreading in servlets

I have some questions (below) relevant to the following code:
public class theServlet extends HttpServlet
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException
         Helper theHelper = new Helper();
         theHelper.setUser(req.getCookies);
         resp.setContentType("text/html");
            PrintWriter out = new PrintWriter(resp.getOutputStream());
            Connection con = null;
         try
               SybDriver sybDriver = (SybDriver) Class.forName("com.sybase.jdbc2.jdbc.SybDriver").newInstance();
               sybDriver.setVersion(com.sybase.jdbcx.SybDriver.VERSION_5);
               DriverManager.registerDriver(sybDriver);
               con = DriverManager.getConnection("jdbc:sybase:Tds:dbsrv1:port/appname", "myuserid", "mypassword");                 if (con != null) {
              if(theHelper.getUserRecord(con, this)) {
                       //do some stuff
                    else { //do some other stuff }
                    con.close();
             }catch(Exception e) { //whatever }
             finally { out.flush(); }
         } //end doGet()
} //end class
public class Helper {
    private String user = "";
    private String field1Val= "";
    private String field2Val= "";
    public boolean setUser(Cookie [] cookies) {
     // method gets the user's userid from a cookie and then:
        user = user_id_from_cookie;
   public boolean getUserRecord(Connection con, theServlet serv){
        StringBuffer sb = new StringBuffer();
        Statement stmt = null;
     try {
         //Try to get the user's info:
            stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
         StringBuffer sql = new StringBuffer("SELECT field1, field2 FROM UserRecords WHERE user_id = '" + user + "'");
         ResultSet rs = stmt.executeQuery(sql.toString());
            rs.last();
            int nrows = rs.getRow();
            if(nrows < 1) { //user doesn't have an entry in the table yet.
             //First, get result set of records with blank userids:
             sql.replace(0, sql.length(), "SELECT * FROM UserRecords WHERE user_id = '' OR user_id = NULL ORDER BY field1");
          rs = stmt.executeQuery(sql.toString());
                rs.last();
                nrows = rs.getRow();
             if(nrows > 0) {
                 //there ARE some records with null user_id, so assign this user to the first one:
                    rs.first();
                 field1Val = rs.getString("field1").trim();
                 field2Val = rs.getString("field2").trim();
                    //QUESTION: IS IT POSSIBLE THAT TWO USERS/THREADS HAVE THE SAME VALUE OF field1Val AT THIS POINT?
                 sql.replace(0, sql.length(), "UPDATE UserRecords SET user_id = '" + user + "' ");
                 sql.append(" WHERE field1 = '" + field1Val+ "' AND user_id is NULL");
              con.setAutoCommit(false);
              //Trying to use transaction isolation to prevent two users from updating the same record.
              //Does this only work if the users share the connection, con?
              int level = con.getTransactionIsolation();
              try {
                  if(con.getMetaData().supportsTransactionIsolationLevel(con.TRANSACTION_READ_COMMITTED)) {
                      con.setTransactionIsolation(con.TRANSACTION_READ_COMMITTED);
                        //SYNCHRONIZE ON SERVLET INSTANCE?
                  //synchronized(serv){
                        nrows = stmt.executeUpdate(sql.toString());
              }catch(SQLException se) {
                     con.rollback();
                     con.setAutoCommit(true);
                     con.setTransactionIsolation(level);
                     stmt.close();
                     return false;
                 con.commit();
                 con.setAutoCommit(true);
                 con.setTransactionIsolation(level);
                    if(nrows < 1) { //couldn't update the db.
                     stmt.close();
                     return false;
                 else {
                     stmt.close();
                     return true;
             else { //There aren't any unused records; deal with it.
                 stmt.close();
                 return false;
            else { // the user has an entry in the table
                rs.first(); //should only be one record for this userid.
                field1Val = rs.getString("field1").trim();
                field2Val = rs.getString("field2").trim();
                stmt.close();
             return true;
        }catch(SQLException se) {
         //some problem not caught elsewhere
         return false;
   } // end getUserRecord
} // end class HelperI should say that the UserRecords table now contains about 5000 records (this will grow in increments of 5000), many of which have null user_id. If the value is not null, then it contains a userid. A user can have either zero or one entry in the table.
Here are my questions:
1. In the servlet, each thread will have its own instance of Helper and of Connection, correct?
2. I want to ensure that only one thread can update a particular UserRecords table record at a time. In the getUserRecord method, please note the line where field1Val is assigned, just above the capitalized QUESTION comment. Is it possible that two threads could have the same value of field1Val at the same time?
3. When I set the transaction isolation level for connection1, does that prevent other threads that are using other connections to the database from accessing records being updated by the thread using connection1?
4. As you can see, I am considering passing a reference to the servlet instance into the getUserRecords method and synchronizing the update statement on the servlet instance. Will that ensure only one thread at a time can update the record, without using the transaction isolation code?
Thanks in advance for your answer.

1. In the servlet, each thread will have its own
instance of Helper and of Connection, correct?True
2. I want to ensure that only one thread can update a
particular UserRecords table record at a time. In the
getUserRecord method, please note the line where
field1Val is assigned, just above the capitalized
QUESTION comment. Is it possible that two threads
could have the same value of field1Val at the same
time?Yes, use synchronized blocks to avoid problems.
3. When I set the transaction isolation level for
connection1, does that prevent other threads that are
using other connections to the database from accessing
records being updated by the thread using
connection1?Yes
4. As you can see, I am considering passing a
reference to the servlet instance into the
getUserRecords method and synchronizing the update
statement on the servlet instance. Will that ensure
only one thread at a time can update the record,
without using the transaction isolation code?Yes.
http://galileo.spaceports.com/~ibidris/

Similar Messages

  • NetBeans Create new Record to Database, How to retrieve it?

    Hi
    I am new to java and using NetBeans and JBoss to develop a new web application now.
    I created a new "ComModule" record to "ComModule" table in database inside my servlet while clicking Add button on my web page.
    The codes are:
    ComModuleFacadeRemote comModuleFacadeRemote = this.lookupComModuleFacade();
    ComModule cm = new ComModule();
    cm.setSerialNumber(serialNo);
    cm.setMacAddress(MACAddress);
    comModuleFacadeRemote.create(cm);
    As in ComModule class, I have set the ComModule ID as sequence and primary key. So this code will add a new reocord by increasing the sequence key automatically.
    What i need to do now is to retrieve the new added record in "ComModule" table and pass it as an Object for other uses.
    e.g. I can do like this:
    ComModule cmObj = comModuleFacadeRemote.getComModuleByID(id);
    BUT the problem now is I don't know the ID of the new added record. How can I retrieve it?
    In ComModuleFacade(), the common method are CREATE, DESTROY, EDIT, FIND, FINDALL. Is there a method that I can directly retrieve a new inserted record??
    Thanks a lot for any of your help...
    Edited by: OhLei on Mar 19, 2008 12:24 AM

    Hi,
      public Long create(name,surname) throws
                SomeException{
            Person person=null;
                try{
                    person=new Person(name,surname);
                    em.persist(object);
                }catch (Exception ex){
                     throw new EJBException("create: " + ex.getMessage());
            return person.getId();  //here it will return your id
        }Person is an entity class with fields id, name, surname.
    Good Luck.

  • In which way Servlet implements  multiThread  without servlet implement Run

    Hi,
    In which way Servlet implements multiThread without servlet implement Runnable.
    In general servletconaainer use one instance of servlet to handle multiple request(except implement SingleThreadmodal).
    I thing that conatainer can achive this ,in this Way
    Myservlet ms;
    1st Way:
    For each new request container call
    new Thread(){
    puvlic void run(){
    ms.service(request,response);
    }.start();
    but I do not thing in this way we get any performace.
    It is better creat pool of Myservelt. and get object from this
    ms1,ms2,ms3
    2nd way is
    Myservlet implement Runnable
    and for each request
    new Myservlet ().start();
    Please tell me In which way conatiner achive multithread of servlet
    Siddharth Singh([email protected])

    You don't need to do any of this. The servlet container starts its own threads, and they call the servlet methods as required. All you have to do is syncrhonize your servlet internally as required to protect anything that needs protecting from multiple threads.

  • Get username from session and retrieve records from database wit tat userna

    hello..
    i got a ChangePassword.jsp which i retrieve the username from session using bean to display on e page..
    <jsp:getProperty name="UsernamePassword" property = "username"/>
    but in my servlet, i wan to retrieve records from database with tat username..
    i tot of coding
    String username = (String)request.getSession().getAttribute("UsernamePassword");
    and then use tat username to retrieve records.. but is that e right way? The page did not display and i got a CastingException..
    Please help.

    If you are using the session inside a jsp, you can say "session" without having to declare it.String usernamePassword = (String) session.getAttribute("usernamePassword");However, right after you get this value, check if it is null:
    if(usernamePassword==null)
    // do sth like forward to error page
    else
    // continue processing
    If it is null, then you are probably not setting it right in the first place. Make sure that in your servlet A you create a session, and before you return or forward to a jsp, that you actually set this value in the session like saying
    session.setAttribute("usernamePassword", usernamePassword);
    and it is case sensitive for the key.

  • How to print all records in database ?

    Hello,
    I am developing a small Database System. Which is used to store some information about student and then print that record, which I want to print. I have used JPanel for Printing single record. As like When I insert student id in TextBox. which is unique. then Click on Search button that is use for searching Record from database. After that the information shown in belowing JPanel. Then using one button for printing this record. It is printing only one record that I have searched. Now what is the problem, I want to print All record from database(can be 500 or 5000) without mentioning any student id in textbox.
    Any type of help Appreciated.
    Thanks in advance.
    Manveer

    Hello Manveer,
    your problem is neither Swing-related or in any other way java specific.
    If you manage to get the data of one student, excellent. Now modify your db-query in the way that the result set returns all students. Loop over the result set and print as usual.

  • Entity Framework doesn't save new record into database

    Hy,
    I have problem with saving new record into database using Entity Framework.
    When I run program, everything seems normal, without errors . Program shows existing, manually added records into the database, and new one too. But new one isn't save into database after running program.
    I've got no idea where's problem. There is code for add new record, show existing.
    Thanks for help!!
    // add new record
    using (var db=new DatabaseEntitiesContext())
    var person = new Table()
    First_Name = "New_FName",
    Second_Name = "New_SName",
    PIN = "4569"
    db.Tables.Add(person);
    db.SaveChanges();
    //show all records
    using (var db=new DatabaseEntitiesContext())
    var selected = from x in db.Tables
    select x;
    foreach (var table in selected)
    Console.WriteLine("{0}{1}{2}",table.First_Name,table.Second_Name,table.PIN);

    Hi BownieCross;
    If you are using a local database file in your project the following may be the cause.
    From Microsoft Documentation:
    Issue:
    "Every time I test my application and modify data, my changes are gone the next time I run my application."
    Explanation:
    The value of the Copy
    to Output Directory property is Copy
    if newer or Copy
    always. The database in your output folder (the database that’s being modified when you test your application) is overwritten every
    time that you build your project. For more information, see How
    to: Manage Local Data Files in Your Project.
    Fernando (MCSD)
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects
    and unknown namespaces.

  • The ABAP/4 Open SQL array insert results in duplicate Record in database

    Hi All,
    I am trying to transfer 4 plants from R/3 to APO. The IM contains only these 4 plants. However a queue gets generated in APO saying 'The ABAP/4 Open SQL array insert results in duplicate record in database'. I checked for table /SAPAPO/LOC, /SAPAPO/LOCMAP & /SAPAPO/LOCT for duplicate entry but the entry is not found.
    Can anybody guide me how to resolve this issue?
    Thanks in advance
    Sandeep Patil

    Hi Sandeep,
              Now try to delete ur location before activating the IM again.
    Use the program /SAPAPO/DELETE_LOCATIONS to delete locations.
    Note :
    1. Set the deletion flag (in /SAPAPO/LOC : Location -> Deletion Flag)
    2. Remove all the dependencies (like transportation lane, Model ........ )
    Check now and let me know.
    Regards,
    Siva.
    null

  • No of records in SAP BI Corresponds to how many records in database

    Dear all
                   If i have 2lakh records in a datasource  then how it  Corresponds to how many records in database.

    For the first time load the datasource , the no of records in the database(source) must be equal to the number of records in the PSA(datasource).
    If you are daily deleting the records in the PSA , and doing a delta load then the no of records in PSA must be equal to the no of records in delta queue RSA7 for the corresponding datasource .
    If the load is a full load everytime or a full repair  ,then the no of  records in PSA  must be equal to the numbers of records in source.

  • Read a text file(database) from a servlet for j2me..?

    Anyone know how to read data from a text file as a database using a servlet for j2me..?
    How to do it..?
    Thanks in advance.

    i tried something like that but there is a NullPointerException... Is what i'm doing correct..?
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class LoginServlet extends HttpServlet {
      private static final String db_server = "localhost/";
      private Connection con = null;
      private String content="";
    public void doPost(HttpServletRequest  request,
                         HttpServletResponse response)
        throws ServletException, IOException
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        String strUserid = request.getParameter("userid");
        String strPassword = request.getParameter("password");
        System.out.println("userid received: " + strUserid);
        System.out.println("password received: " + strPassword);
         try{
                   System.out.println("opening the file....");
                   //String url = "file://"+dbServer+"test.txt";
                   //String uri = "file://localhost/test.txt";
                   String uri = "file://Program Files\Apache Group\Tomcat 4.1\webapps\Project\WEB-INF\classes\trial\test.txt";
                   //String uri = "file:/database/res/test.txt";
                   System.out.println( uri );
                   InputConnection conn = (InputConnection) Connector.open( uri,Connector.READ );
                   System.out.println("connection established");
                   InputStream in = conn.openInputStream();
                   int ch;
                   conn.close(); // doesn't close input stream!
                   System.out.println( "Contents of [" + uri +"]" );
                   while( ( ch = in.read() ) != -1 ){
                   System.out.print( (char) ch );
                   in.close();
                   catch( ConnectionNotFoundException e ){
                  System.out.println( e.toString()+"File could not be found!" );
                  System.out.println( "File could not be found!" );
                   catch( IOException e ){
                       System.out.println( e.toString() );
                   catch( Exception e ){
                       System.out.println( e.toString() );
          out.close();
        } // End try
        catch (Exception e) {
          System.out.println("Exception in doPost(): " + e.getMessage() );
      } // End doPost
    } // End loginServlet

  • Fetch records from Database based on Input value

    Hi Experts,
    In my mobile application, I have designed one input field with F4 help or input assist. I need to fetch records from database based on that input and need to display records in table.
    My question is:
    How to fetch the records from database/back end based on the input value and display them as table format as we are doing in SAP ABAP?
    Here, I need to fetch the records based on input value available in the UI screen and pass that value to gateway, fetch the records from database and need to bind with table in SAPUI5.
    Kindly share the whole process flow with sample code for this requirement. Hope I have explained the requirement in detail.
    Thanks In Advance..
    Regards,
    Arindam Samanta.

    Hi,
    Try something like this.
    In this, I am passing From date, To date, RelGrp, RelStr, Uname as input. Then I am storing those values in variables and passing this data in Odata request.
    OData.read({ requestUri: "http://xxxx:8000/sap/opu/odata/sap/Z188_PO_SRV/pos?$filter=Docdate le datetime'"
                    + todateformat+"T00:00:00' and Docdate ge datetime'"
                    + fromdateformat+"T00:00:00' and RelGrp eq '"
                    + relcode +"'and RelStr eq '"
                    + relstg +"'and Uname eq '"
                    + username+ "' "},
      function (data) {
    console.log(data);
    When we are giving correct inputs it will goes to Success function and get the data from back end.
    In console we can see the data.
    Hope this will helps to you.
    Thanks&Regards
    Sridevi

  • Add a new record in database table without using table maintance generator

    Hi Expart ,
                  Plz. tell me how to add new record in database table without using table maintance ganerator ....give me one ex.
    Regards
    Bhabani

    Hi,
    The other way to safely handle the modification of tables is through is by programs that can be done with SE38 or SE80.
    To insert into database table we use INSERT statement :
    1. To insert a single line into a database table, use the following:
    INSERT INTO <target> VALUES <wa>.
    INSERT <target> FROM <wa>.
    2. To insert a several lines into a database table, use the following:
    INSERT <target> FROM TABLE <itaba>.
    Or even we can use MODIFY statementas this single statement is used to insert as well as update the records of database table.
    MODIFY <target> FROM <wa>.
    or MODIFY <target> FROM TABLE <itab>.
    thanx.
    Edited by: Dhanashri Pawar on Sep 10, 2008 12:25 PM
    Edited by: Dhanashri Pawar on Sep 10, 2008 12:30 PM

  • How to write code to insert record in database programtically in Jdev rel

    Hi Experts,
    Please tell me how to write code to insert record in database programtically in Jdev rel .2.
    Thanks
    Shiv Naresh

    To insert the record programmatically i will provide you some sample below
    ViewObject vo = this.getVoXXXX();
    Row vor = vo.getCurrentRow();  // get the current row of the record
    ViewObject vo1 = this.getvoYYYY();
    Row vor1 = vo1.createNewRow(); //creating new row in the table
    vor1.setAttribute("aaaaa",vor.getAttribute("ttttt")) // In this we are getting the current row value of "ttttt" and inserting into "aaaaa"Hope this could help you!

  • How to delete a record in database it should be effect in XML

    In my application wheni insert a record in database it automatically inserted in XML now my problem is when i delete a record in database it should also effect in XML
    plz anybody anything knows about this reply me

    First up all, when u insert a record in database, how the data is inserted in xml file. Is there any application written for that?
    So when u delete the record from database,and want that same data should be deleted from the xml file, write a application to delete data from xml, and call that when u delete record from database.
    U can Write application using DocumentBuilderFactory.
    And using XQuery, you can delete data from xml.
    Hope this will help u.
    .....yogesh

  • Insertion of an error report was throttled to prevent flooding of the Call Detail Recording (CDR) database

    Hello,
    One of my Lync 2013 standard front-end servers is frequently logging this error:
    Log Name:      Lync Server
    Source:        LS Data Collection
    Date:          28/12/2012 10:04:05
    Event ID:      56208
    Task Category: (2271)
    Level:         Warning
    Keywords:      Classic
    User:          N/A
    Computer:      LYNC-FE2.mydomain.local
    Description:
    Insertion of an error report was throttled to prevent flooding of the Call Detail Recording (CDR) database.
    Component: CDR Adaptor
    Cause: This is an expected condition if too many error reports of the same type were reported at the same time.
    Resolution:
    No action is needed. A large enough number of error reports of this type have already been inserted into the database and can be used for troubleshooting and reporting. Additional errors are not inserted to avoid flooding of the database with redundant information.
    Event Xml:
    <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
      <System>
        <Provider Name="LS Data Collection" />
        <EventID Qualifiers="35039">56208</EventID>
        <Level>3</Level>
        <Task>2271</Task>
        <Keywords>0x80000000000000</Keywords>
        <TimeCreated SystemTime="2012-12-28T10:04:05.000000000Z" />
        <EventRecordID>10745</EventRecordID>
        <Channel>Lync Server</Channel>
        <Computer>LYNC-FE2.mydomain.local</Computer>
        <Security />
      </System>
      <EventData>
        <Data>CDR Adaptor</Data>
      </EventData>
    </Event>
    I don't appear to have any problems or issues with Lync at all. Full Enterprise Voice is in use at this site.
    Anyone know why this may be occuring?
    Thanks,
    Ben

    Did you check any additional errors? I'm seeing the same issue and linked it to this actual error message that seems to point towards a broken data model or bugged type casting/checking in the interface:
    Failed to execute a stored procedure on the back-end.
    Component: CDR Adaptor
    Stored Procedure: RtcReportError
    Error: System.Data.SqlClient.SqlException (0x80131904): Error converting data type varchar to float.
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at Microsoft.Rtc.Common.Data.DBCore.Execute(SprocContext sprocContext, SqlConnection sqlConnection, SqlTransaction sqlTransaction)
    ClientConnectionId:xxxxxxxxxxxxx
    Cause: Configuration issues, an unreachable back-end or an unexpected condition has resulted in the error.
    Resolution:
    Verify the back-end is up and this Lync Server has connectivity to it. If the problem persists, notify your organization's support team with the relevant details.

  • Retrive last inserted  record  from database table

    Hi,
    some body inserting a record into table 'A' through some procedure/java program.i want to retrive the last inserted record from database table.records are not stored in order.Can any body help me.

    In general, unless you are storing a timestamp as part of the row or you have some sort of auditing in place, Oracle has no idea what the "first" or "last" record in a table is. Nor does it track when a row was inserted.
    - If you have the archived logs from the point in time when the row was inserted, you could use LogMiner to find the timestamp
    - If the insert happened recently (i.e. within hours), you may be able to use flashback query to get the value
    - If you're on 10g or later and the table was built with ROWDEPENDENCIES and the insert happened in the last few days and you can deal with a granularity of a few seconds and you don't need 100% accuracy, you could get the ORA_ROWSCN of the row and convert that to a timestamp.
    If this is something you contemplate needing, you need to store the data in the row or set up some sort of auditing.
    Justin

Maybe you are looking for

  • Screen Sharing and Wake from Sleep

    Hi, I'd like to know if there's any way a Screen Sharing request from a remote vnc client can wake a Leopard machine from sleep. I've opened the vnc port on firewall, tested screen sharing while its awake... all good. When the target machine is aslee

  • ABAP Dump when executing tcode CATS_APPR_LITE for multiple selection.

    Dear Members, Issue: When executing tcode CATS_APPR_LITE for Time Approval from the remote R/3 by selecting multiple selections and click on Approve, if you get a dump saying CALL_FUNCTION_REMOTE_ERROR Analysis: If there is an SAP Note applied in 136

  • Music not showing up in purchased section

    Hey there, I bought several song a couple of weeks ago. They used to show up in purchased song section in the music app, but now they dont and the album artworks seem to be gone. how can I fix this is really annoying.

  • Additional Pageflow - JavaScript Questions

    I was hoping someone (bea employee???) could answer a couple more JavaScript questions for me?? First one is how do I (can I) do something similar to what John Rohrlich (see below) suggested inside a netui-data:grid tag? Among other things that didn'

  • Photoshop changes not saving in Aperture

    Greetings, I'm having a frequent but inconsistent problem that when I open images in Photoshop. After saving the changes and closing the PS file, the copy is still there in Aperture but it remains a copy of the original, it does not record any change