Preventing Multiple Init problem

Hello,
This is something I should already now, but I have myself stumped.
I have a servlet that has some static instance variables to some singleton objects, and some Strings and some other objects, which get initialized in the init() method when my servlet gets loaded. When another instance of my servlet is created, I don't want it to re-initialize those objects. For most of them it would be okay, but there are a few that would cause problems. So, I was wondering what would be a good way to ensure that a servlet only initialized certain instance variables once, and any future servlet instances would skip that initialization and use the values that were already initialized by the first instance? I wrote the following test program:
public class TestBool
     static boolean testBool;
     static String testString;
     public static void main(String[] args)
          Thread main = Thread.currentThread();
          System.out.println( (testString == null ? "true":"false") );
          testString = "no";
          try
               main.sleep(30000);
          catch(Exception e)
               e.printStackTrace();
}I then ran it once, then ran another instance of it, but the second instance seems to reset that testString to null when it runs, so they both output "true"... I am also assuming that both instances I ran were running in the same JVM. So, I am assuming the same thing may happen to my servlets. Any advice and/or expertise would be greatly appreciated! Thanks!

I am using a multi-threaded servlet, but from my
understanding, it is still possible to end up with
more than one instance of a multi-threaded servlet if
there is enough load on the server that it needs to
create another instance to serve all the requests.
(Let me know if that is incorrect).According to the servlet spec, the container must use only one instance of a multi-threaded servlet class. Load does not impact this because the server can create more threads - another instance would not help. However, it's probably safer to code defensively because it's possible that your servlet could be changed later to a single thread servlet and who knows if all servlet engines follow the spec.
I guess
my real question is, when it goes to create another
instance... will the static declarations reset the
references to null, or should I be able to check if
fooString is null and skip initialization if it is not
null?The static declarations are initialized when the class is loaded, so object creation has no impact. To be super-safe, you should synchronize the code that initializes the variables. In my previous post I synchronized on the object but it should have been on the class.
public void init(ServletConfig config) throws ServletException {
      if (fooString == null) {
            synchronized (FooServlet.class)
                if (fooString == null) {
                    fooSingleton= SingletonClass.getInstance();
                    fooString = config.getInitParameter("fooValue");
}All of this is probably more safety than you need! There should be only one instance of the servlet, and this code handles multiple instances being created concurrently. As long as the app is not distributable across multiple JVMs, then you should be ok.

Similar Messages

  • How to prevent multiple logins by using HttpBindingListener

    Hi,
    Can anyone tell me how do i actually use session to prevent multiple login from different machine? From my understanding, i need to use HttpBindingListener to valueBound and valueUnbound when user tries to login, but i encounter a problem is my session is always overwritten since i use setAttribute() method in servlet.
    For instance i use username(aaa & bbb) to login in two different machine, my login is always overwritten if i use username bbb to login after username aaa. i know it is because setAttribute() method overwrite existing session data, so i would like to know what other method should i use to achieve what i want, tks.

    Hi,
    This is the logic for session :
    Connect to db for verification, once verified, system return a UserBean and this UserBean will be set in ClientSecurityEngine
    When this particular user has been successfully verified, a new session will be created
    if(success)
        session = request.getSession();
        User user;
        synchronized(session)
        user = (User) session.getAttribute("user");                       
        if(user == null)
           user = new User(ClientSecurityEngine.getInstance().getUserBean().getUsername());
           session.setAttribute("user", user);
    /* User class */
    public class User implements HttpSessionBindingListener {
        private static Map<String, HttpSession> logins = Collections.synchronizedMap(new HashMap<String, HttpSession>());
        private String username;
        public User(String username) {
            this.username = username;       
        public String getUsername() {
            return username;
        @Override
        public void valueBound(HttpSessionBindingEvent event) {
            if (logins.containsKey(getUsername())) {
                HttpSession session = logins.remove(getUsername());
                if (session != null) {
                    session.invalidate();
                logins.put(getUsername(), event.getSession());
            } else {
                logins.put(getUsername(), event.getSession());
        @Override
        public void valueUnbound(HttpSessionBindingEvent event) {
            logins.remove(getUsername());
    }Edited by: EJP on 21/07/2011 14:22: added {noformat}{noformat} tags so we can actually read your code. Please use them.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Inventory Init Problem

    Hello
          I have some problem for Init request,there is very much data while data schedule in BI side.and i have only 3 to 4 hours to take init and data fill from setup table to bi(Schedule).so what i do.kindly provide solution for that problem

    Hi,
           Generally, you need to parallelize your init ranges first in R/3.   You can follow the same in BW Infopackages by doing multiple init with different ranges, so that the jobs can parallely run.  There is one more scenario wherein you can do Init without data transfer in BW (given that you have done your Init with some ranges in R/3 Side to fill setup tables) and continue your deltas.  Then perform your full loads with some ranges to run in parallel when there is smaller load on servers.  Finally do the repair full request and continue your deltas.  Hope it should provide you some answers of minimizing your down time.
    Thanks
    Kishore

  • How to prevent multiple submit (replay attack)?

    Hi there, I have managed to submit the form to the server side. However, is there any way to prevent the client side from keep submitting the form? I have heard of using random number, but I don't know what javascript code to place in the web page. Can anybody help, because I am stuck in the problem for quite a long time.
    Thanks,
    Rocky.

    r0ckytay89 wrote:
    Hi there, I have managed to submit the form to the server side. However, is there any way to prevent the client side from keep submitting the form? I have heard of using random number, but I don't know what javascript code to place in the web page. Can anybody help, because I am stuck in the problem for quite a long time.
    Thanks,
    Rocky.Well there are two ways of implementing this.
    1).Javascript Solutions (and mind you never always try disabling the submit button )
    [http://www.elated.com/articles/preventing-multiple-form-submits/]
    [http://www.web-source.net/web_development/form_submission.htm]
    2).Maintaining state of the form on server side and using a token for preventing mutiple submits.
    try to go through the solutions recommended in the below articles
    [http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=50&t=016689]
    [http://faq.javaranch.com/java/HowToPreventMultipleFormSubmits] (In struts)
    Or a more generalized solution is given in the article below
    [http://www.onjava.com/pub/a/onjava/2003/04/02/multiple_submits.html]
    Hope that might help :)
    REGARDS,
    RaHuL

  • How to prevent multiple users from updating the same data in coherence

    Hi,
    I have a Java Web Application and for data cache am using coherence 3.5. The same data maybe shared by multiple users which maybe in hundreds. Now how do I prevent multiple users from updating the same data in coherence i.e. is there something in coherence that will only allow one user a time to update. If one user is in a process of updating a data in coherence and some other user also tries to update then the second user should get an error.
    Thanks

    I have a question on the same line. How can I restrict someone from updating a cache value when I a process is already working on it. I tried locking the cache key but it does not stop other process to update it , it only does not allow other process to get lock on it.

  • Prevent multiple users from editing/approving the same form SPD 2013,SP 2013

    Hello all, I have a workflow with a to do task, the task is assigned to a group so any of the users in that group can go in and do a quality check on form data and approve it.  How do I prevent multiple users from working on the
    same form? do I just require check out? or is there a way to notify the rest of the group that a user has already started the quality check.

    The "Require Checkout" option is your best bet.  You can also enable the auto checkout on edit option to allow minimal effort on the side of the user.  Other users will then get the error message stating the item is checked out, if they try to
    edit it.
    If you'd like, you could add a workflow to the task list that triggers when something is changed.  That workflow can check if the item is checked out and if so, email the other users assigned to the task.
    I trust that answers your question...
    Thanks
    C
    |
    RSS |
    http://crayveon.com/blog |
    SharePoint Scripts | Twitter |
    Google+ | LinkedIn |
    Facebook | Quix Utilities for SharePoint

  • Prevent multiple users from updating coherence cache data at the same time

    Hi,
    I have a web application which have a huge amount of data instead of storing the data in Http Session are storing it in coherence. Now multiple groups of users can use or update the same data in coherence. There are 100's of groups with several thousand users in each group. How do I prevent multiple users from updating the cache data. Here is the scenario. User logs-in checks in coherence if the data there and gets it from coherence and displays it on the ui if not get it from backend i.e. mainframe systems and store it in coherence before displaying it on the screen. Now some other user at the same time can also perform the same function and if don't find the data in coherence can get it from backend and start saving it in coherence while the other user is also in the process of saving or updating. How do I prevent this in coherence. As have to use the same key when storing in coherence because the same data is shared across users and don't want to keep multiple copies of the same data. Is there something coherence provides out-of-the-box or what is best approach to handle this scenario.
    Thanks

    Hi,
    actually I believe, that if we are speaking about multiple users each with its own HttpSession, in case of two users accessing the same session attribute in their own session, the actually used cache keys will not be the same.
    On the other hand, this is probably not what you would really like, you would possibly like to share that data among sessions.
    You should probably consider using either read-through caching with the CacheLoader implementor doing the expensive data retrieval (if the data to be cached can be obtained outside of an HTTP container), or side caching with using Coherence locks or entry-processors for concurrency control on the data retrieval operations for the same key (take care of retries in this case).
    Best regards,
    Robert

  • How can i design my application to prevent multiple login

    i need to develop a new application which want to prevent multiple user login. How can i do that? if i put all userid in a stack/arraylist and set it global, then set a filter to check the stack each time, is it ok, or have another better solution to do that. Thanks.

    Your client application needs to contain a unique Session identifier and the server application needs to keep a mapping of these Session identifiers against the User that is logged in.
    Then if another client app trys to log in with the same User ID and it is not the same as the current logged in Session identifier for that User, you can deny them access.
    Make sure the client app has a mechanism for logging out the current User/Session identifier, by way of a button or event.
    Events may go as follows:
    1. User A logs in
    2. Server app creates Session ID 1.
    3. Client app is assigned Session ID 1.
    4. Server app maps User A to Session ID 1.
    then later
    5. Different user tries to log in as User A.
    6. Server app checks for Session ID.
    7. No Session ID exists.
    8. Not the same user - go away (or other instruction)
    or
    5. Original User A (from point 1) logs in again.
    6. Server app checks for Session ID.
    7. Client app sends Session ID 1.
    8. Server app checks mapping of Session ID 1 to User A.
    9. Success, User A is the original user - please continue what you're doing.
    How you implement the storing of the Session ID on the Client app is dependant on the type of app your building - Cookies for web apps or encrypted files for GUI apps. The same applies for storing the mapping of the User to the Session but a database is the easist route to follow.
    Hope this helps.

  • F110 - How to prevent multiple creation of DME file?

    Hello,
    I need to prevent multiple creation of DME file for the same Payment Run (after it has been created once).
    "Printout" bottom creates DME file and Payment Advice any time you trigger it.
    I'm searching for some User Exit / BAdi / Function that will help me to add ABAP code that will check if DME file has already been created.
    Thank You in Advance

    Hello,
    Please check if the flag "Create payment medium" is not flagged at the proposal and the payment run file.
    If it is flagged the payment file will be generated. Also when you press the print out button, the print program will be called and the system will try to created a new payment file.
    In order to avoid duplicated payments you should consider using the flag 'Payment Document Validation" in your print program.
    If the 'Payment Document Validation' parameter is not set ON, documents already processed for payment can be selected and paid again in a subsequent payment run, when posting terminations have occurred.
    Please refer to SAP Knowledge Base Article 1713825 in order to activate Payment Document Validation.
    Another option is to suppress  the"Create Payment Medium" flag at Proposal Run.
    In this case you should check the following information:
    Please restrict the activity 15 of object F_REGU_BUK in the user
    profile/role
    You may also refer to the available activities on this:
    - 02 Edit parameters
    - 03 Display parameters
    - 11 Execute proposal
    - 12 Edit proposal
    - 13 Display proposal
    - 14 Delete proposal
    - 15 Create payment medium proposal
    - 21 Execute payment run
    - 23 Display payment run
    - 24 Delete payment run payment data
    - 25 Create payment media of payment run
    - 26 Delete payment orders of payment run
    - 31 Print payment medium manually
    Kind Regards,
    Fernando Evangelista

  • How do I prevent multiple applications opening on start up with Lion?

    how do I prevent multiple applications opening on start up with Lion?

    It's the Resume feature of Lion:
    Managing Mac OS X Lion's application resume feature.
    If you shutdown your computer you should get a dialog asking if you want applications to resume on the next startup. Simply uncheck the box to prevent that from occurring. Open General preferences and uncheck the option to Restore windows when quitting and re-opening apps. You can also install a third-party utility to control resume features on individual applications: RestoreMeNot or Application State Cleaner.

  • Multiple Inheritance problem persists in Interfaces

    Hi,
    I tentatively made a program and found that multiple inheritance problem of C++ persists even with interfaces. Although this is definetely a special case but I want to know what is this problem known as( i know that this is perhaps known as diamond problem in C++). And is there a way out of this thing.
    interface one
         int i=10;
    interface two
         int i=20;
    interface z extends one,two
    public class xyz implements z
         public static void main(String [] a)
         System.out.println(i);
    }O/P
    D:\Education\Java\JavaStudyRoom\Applets>javac xyz.java
    xyz.java:16: reference to i is ambiguous, both variable i in one and variable i
    in two match
    System.out.println(i);
    *^*
    *1 error*
    Thanks for replying

    suvojit168 wrote:
    I tentatively made a program and found that multiple inheritance problem of C++ persists even with interfaces. Although this is definetely a special case but I want to know what is this problem known as( i know that this is perhaps known as diamond problem in C++). And is there a way out of this thing. This is not the so called diamond inheritance problem. What you have here is an ordinary name clash. And as has been noted you can resolve it by qualifying which constant you're referring to, like
    System.out.println(one.i);
    For the diamond inheritance problem to apply both the one and the two interfaces would need to inherit a common ancestor (that's how the diamond is formed). Furthermore the common anscestor would need to carry implementation which would then be inherited two ways, once via one and once via two. This is the diamond inheritance problem Java is avoiding by allowing single inheritance of implementation only.
    P.S. My previous post was posted my mistake.

  • Are multiple inits with different selection criteria possible for LO

    Extractor 2lis_02_itm?
    Thanks
    Reddy

    Hi
    we use the multiple init scenario whenever there are huge data volumes for initialization and just to get the set up tables filled up in case of LO extraction, with minimum downtime (as the downtime can take upto 2-3 days) so as not to affect the users and also risk losing data, we do multiple inits to reduce the downtime and get the set up tables filled up.
    Yes in your extractor you can but be careful the selection crieteria does not overlap
    Hope this helps
    Anand Raj

  • SP10 - multiple approver problem with CUP

    We have SP10 (patch 1) in our development system and cannot move forward to production because of a real show stopper.  I have currently reported this to SAP thru an OSS message (and it is in development) but would like to know if anyone else is having this issue with SP10.  (this happened even before applying patch 1)
    We have multiple approvers when creating NEW users or CHANGING users in CUP.  We have it configured to allow just one of the approvers to approve before going on to the next stage.  Since we put in SP10, CUP is requiring ALL approvers to approve the request before going on to the next stage.  We get the following message when one of the approvers approve the request:  Request no: 5020. is approved, pending for other Approvers. 
    I've seen this reported for UAR and SOD but not for CUP.  In fact, there is a fix for UAR in Patch 1 of SP10.  I applied this patch but it hasn't fixed the CUP issue.  I also don't have the issue when rejecting a CUP request, or when approving it through the configuration --> Request --> Administration screen (what I consider the Back-door since only security administrators get the configuration area).
    Thanks for your input.
    Peggy

    Christian,
    I totally agree with you.
    The good news is.... We installed SP11.1 and the multiple approver problem is fixed. 
    We have decided to leave our production system at SP8 until this system settles down a bit.  Of course, this means we can't use many of the new fixes and features (such as UAR).  We use our sandbox system to apply new support packs and do very rigorous testing.  And our DEV system is at SP8 too.
    Good Luck.
    Peggy

  • Multiple INITs

    Is it possible to do multiple INITs with differing selection critera in an InfoPackage?
    Ashmith Roy

    Hi Ashmith,
    Yes, it is possible to do more than one init, provided you are using non-overlapping selection criteria. Take a look at this link for more info:
    http://help.sap.com/saphelp_nw04/helpdata/en/80/1a65dce07211d2acb80000e829fbfe/content.htm
    Hope this helps...

  • Prevent multiple personnel actions being performed on the same day

    Hi Experts,
    Does anyone know if it is possible to prevent multiple personnel actions from being performed on the same day even where the action does not change the status of the employee?
    Regards,
    Janet

    Hi Janet,
    i mean to say if you activate the additional action then only the second action on the same day gets stored in to the IT-0302.
    if you dont activate additional actions then if you run the second action on same day it will over write the existing record and gives warning message that  this record over write the existing record.
    so here the point is if additional actions is activated then only system allows you to perform the second action on same day..
    other wise it will replace the existing record.
    if you want to prevent the additional actions to be prevented even after activating it --i think its not possible because the functionality of the IT 0302 is to save more than one record.
    yes you can restrict the to perform the action through authorizations 
    hope it is clear 
    regards,
    mohammed

Maybe you are looking for

  • 10.1.3.4 - How to access custom java methods in worklist ?

    We want to invoke a custom java method inside of worklist, when the file attachments are added to the worklist. We are planning to modify the auto-generated jsp page to do the same. We have created the custom jar files, but am not sure where to deplo

  • Database issue

    Hi All, I have a small problem with the database (mysql) that i have set up. So to start off the website is for a funeral directors, within this site is a page where people can donate (http://www.milesfunerals.com/donations_2.php ), they put the name

  • Set Tolerance Limits for Price Variance for PR missing from SPRO

    I'm looking into setting up tolerance limits for price variance at the PR level. But when i navigate here: SPRO > Materials Management > Purchasing > Purch.requisition > Set Tolerance Limits for Price Variance I'm not seeing that available in SPRO. I

  • 5g video ipod owners: Don't upgrade to iTunes 7.0 (or 1.2)

    If your ipod (mine is a 5th. gen 60g version), is working well, (as mine was...), then, by all means, do NOT update to iTunes 7.0, (or the iPod to 1.2) The iTunes update seems to be o.k., but the 1.2 iPod updater totaly messed up my pod! Cannot selec

  • Internet Explorer 9, 10, or 11

    Internet Explorer 9, 10 or 11 is not showing up in my updates to deploy.  I have Updates and Update Rollups selected under Classifications in Software Update Point Component and I'm getting Internet Explorer updates, but not the application IE.  I ha