Global Component - How is it thread safe?

While a global component is serving many sessions and in turn many requests, how is the thread safety guaranteed? How the call stack is maintained?

It's often possible to write a global component that is thread safe without using locks or synchronize. As long as the component's class member variables are set globally, e.g., via Nucleus configuration, and all thread-specific values are held in method variables (which are housed on the stack), the component is thread safe. If thread-specific values need to be accessed by multiple methods in the class, the values must be passed as formal method parameters rather than through class member variables. Most of the global components that ship in the ATG product stack follow this coding pattern and do not use any kind of locks.

Similar Messages

  • How to write thread safe to a file..please help!!

    Hi,
    need a sample writing thread safe to a file.
    thanks

    `Or create a class that has a private BufferedWriter to the file, opened in append mode, and in your "print" or "write" method, synchronize on the BufferedWriter..ie...
    given a BufferedWriter bw that's already open to append mode.
    public void write(String s)
    synchronized(bw)
        bw.write(s);
        bw.flush(0;
    }

  • How to make thread safe?

    Hi guys,
    I got a backing bean like
    public class UserBean{
    private String firstname;
         public String getFirstname() {
              return firstname;
         public void setFirstname(String firstname) {
              this.firstname = firstname;
    the firstname variable is also use in the jsp page like
    <h:outputText value="#{userBean.firstname}"/>
    If the "setFirstname" method is executed by two threads, then it's likely that the value of the firstnameinstance variable will be replaced by the second thread while the first thread is still using it. So does JSF handle this thread safe condition? Please advice, Thanks !
    regards,
    kmthien

    If the bean is scoped in the request, according to the servlet spec, only one thread should ever access it. If the bean in scoped in the session/application, then it's up to you to manage synchronization within your bean as with every other web framework.

  • Calling repricing from a global component

    Hi ,
    I want to invoke repricing from my global component,how should i do it.whatever way i found , it required some or other parameters which are not available globally.
    Scenario :
    In my requirement i need to remove some items from order using global components like Droplets,Processors etc.
    I have extended CommerceItemManager's removeItemFromOrder method to suit my needs , the issue is that after remove item from order , i need to invoke repricing (which is automatically invoked when we use form handlers, but here this is not the case ).
    i was thinking of calling :
    getPurchaseProcessHelper().runProcessRepriceOrder(pPricingOperation, pOrder, pPricingModels, pLocale, pProfile, pExtraParameters, pErrorHandler)
    how should i get pPricingModels, pLocale, pProfile, pExtraParameters, pErrorHandler params in my global components.
    Note - I dont want to use RepriceOrderDroplet, i want to do it programatically.
    Please suggest.
    Thanks
    ~Praveer

    This may help you.
    ================================================================
    DynamoHttpServletRequest dynReq = ServletUtil.getCurrentRequest();
    OrderHolder shoppingCart = (OrderHolder) dynReq.resolveName(getShoppingCartCompPath());
    Profile profile = (Profile)dynReq.resolveName(getProfilePath());
    OrderManager orderManager = (OrderManager)dynReq.resolveName(COMPPATH_ORDERMANAGER);
    Locale localeVal = getLocale2reprice(shoppingCart.getCurrent(), dynReq);
    PricingModelHolder userPricingModels = (PricingModelHolder) dynReq.resolveName(COMPPATH_PRICING_MODELS);
    Map<String, Object> parameterMap = new HashMap<String, Object>();
    parameterMap.put(PRICING_OP, ORDER_TOTAL);
    parameterMap.put(PRICING_MODELS, userPricingModels);
    parameterMap.put(LOCALE, locale);
    parameterMap.put(PROFILE, profile);
    parameterMap.put(ORDER, shoppingCart.getCurrent());
    parameterMap.put(COMPNAME_ORDERMANAGER, orderManager);
    PipelineResult result = getPurchaseProcessHelper().getPipelineManager().runProcess(repriceChainIdName, parameterMap);
    if(pipelineResult != null && pipelineResult.hasErrors()){
    Object[] errors = pipelineResult.getErrors();
    for (Object currError : errors){
         //you would collect errors here; which can be passed to the invoker
    private Locale getLocale2reprice(Order orderVal, DynamoHttpServletRequest dynReq){
    Locale locale2reprice = null;
    String localeVal = orderVal.getLocale();
    if (localeVal == null){
    RequestLocale reqLocaleVal = dynReq.getRequestLocale();
    if (reqLocaleVal != null && reqLocaleVal.getLocaleString() != null){
    localeVal = reqLocaleVal.getLocaleString();
    if (localeVal != null){
    locale2reprice = new Locale(localeVal);
    return locale2reprice;
    ================================================================
    NOTE: The respective profile & order components will be loaded for the logged-in customer.
    So, dynReq.resolveName(profile/shoppingCart) will get the right values in the global scoped component.
    Edited by: user1697061 on May 13, 2012 3:59 PM

  • How to make a global scope component to be thread safe?

    One of my global component preserves states in its member variables, I am afraid that it's might messed up in multi-threading conditions, so how to make a nucleus global component to be thread safe?
    Edited by: user13344577 on Jul 14, 2011 9:45 AM

    Hi,
    Just to help integrate Shaik's and my own seemingly contradictory replies:
    If the member variables in your global component actually need to be globally available, so that multiple threads/sessions need to seem the same data, then you need to use synchronization or some scheme to make this data thread-safe when updating it. If the member variables are non-global data and are simply for convenience of having data available for multiple method calls or something like that, then you should do as I said (don't use synchronization) and use one of my suggestions to avoid this.
    I have seen customers frequently do what I replied about and store non-global data in a global component, and Shaik simply interpreted what "user13344577" is trying to do differently. Clarification is needed to know which of our answers better applies.
    Thanks.
    Nick Glover
    Oracle Support for ATG Products

  • How can I use a Selector in a thread safe way?

    Hello,
    I'm using a server socket with a java.nio.channels.Selector contemporarily by 3 different threads (this number may change in the future).
    From the javadoc: Selectors are themselves safe for use by multiple concurrent threads; their key sets, however, are not.
    Following this advise, I wrote code in this way:
             List keys = new LinkedList(); //private key list for each thread
             while (true) {
              keys.clear();
              synchronized(selector) {
                  int num = selector.select();
                  if (num == 0)
                   continue;
                  Set selectedKeys = selector.selectedKeys();
                  //I expected this code to produce disjoint key sets on each thread...
                  keys.addAll(selectedKeys);
                  selectedKeys.clear();
              Iterator it = keys.iterator();
              while (it.hasNext()) {
                  SelectionKey key = (SelectionKey) it.next();
                  if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
                   Socket s = serverSocket.accept();
                   SocketChannel sc = s.getChannel();
                   sc.configureBlocking( false );
                   sc.register( selector, SelectionKey.OP_READ );
                  } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
    //.....Unfortunately synchronizing on the selector didn't have the effect I expected. When another thread select()s, it sees the same key list as the other thread that select()ed previously. When control arrives to serverSocket.accept(), one thread goes ahead and the other two catch an IllegalBlockingModeException.
    I'm not willing to handle this exception, the right thing to do is giving disjoint key sets to each thread. How can I achieve this goal?
    Thanks in advance

    A single thread won't be enough cause after reading data from the socket I do some processing on it that may take long.So despatch that processing to a separate thread.
    Most of this processing is I/O boundI/O bound on the socket? or something else? If it's I/O bound on the socket that's even more of a reason to use a single thread.
    Anyway I think I'll use a single thread with the selector, put incoming data in a queue and let other 2 or 3 threads read from it.Precisely. Ditto outbound data.
    Thanks for your replies. But I'm still curious: why is a selector thread safe if it can't be used with multiple threads because of it's semantics?It can, but there are synchronization issues to overcome (with Selector.wakeup()), and generally the cost of solving these is much higher than the cost of a single-threaded selector solution with worker threads for the application processing.

  • Native library NOT thread safe - how to use it via JNI?

    Hello,
    has anybody ever tried to use a native library from JNI, when the library is not thread safe?
    The library (Windows DLL) was up to now used in an MFC App and thus was only used by one user - that meant one thread - at a time.
    Now we would like to use the library like a "server": many Java clients connect the same time to the library via JNI. That would mean each client makes its calls to the library in its own thread. Because the library is not thread safe, this would cause problems.
    Now we discussed to load the library several times - separately for each client (for each thread).
    Is this possible at all? How can we do that?
    And do you think we can solve the problem in this way?
    Are there other ways to use the library, though it is not thread safe?
    Any ideas welcome.
    Thanks for any contributions to the discussion, Ina

    (1)
    has anybody ever tried to use a native library from
    JNI, when the library (Windows DLL) is not thread safe?
    Now we want many Java clients.
    That would mean each client makes its calls
    to the library in its own thread. Because the library
    is not thread safe, this would cause problems.Right. And therefore you have to encapsulate the DLL behind a properly synchronized interface class.
    Now the details of how you have to do that depends: (a) does the DLL contain state information other than TLS? (b) do you know which methods are not thread-safe?
    Depending on (a), (b) two extremes are both possible:
    One extreme would be to get an instance of the interface to the DLL from a factory method you'll have to write, where the factory method will block until it can give you "the DLL". Every client thread would obtain "the DLL", then use it, then release it. That would make the whole thing a "client-driven" "dedicated" server. If a client forgets to release the DLL, everybody else is going to be locked out. :-(
    The other extreme would be just to mirror the DLL methods, and mark the relevant ones as synchronized. That should be doable if (a) is false, and (b) is true.
    (2)
    Now we discussed to load the library several times -
    separately for each client (for each thread).
    Is this possible at all? How can we do that?
    And do you think we can solve the problem in this
    way?The DLL is going to be mapped into the process address space on first usage. More Java threads just means adding more references to the same DLL instance.
    That would not result in thread-safe behavior.

  • How to know whether a method is thread-safe through the java-doc?

    In some book, it says that SAXParserFactory.newSAXParser() is thread-safe,but in the java-doc,it doesn't say that.
    newSAXParser
    public abstract SAXParser newSAXParser()
    throws ParserConfigurationException,
    SAXExceptionCreates a new instance of a SAXParser using the currently configured factory parameters.
    Returns:
    A new instance of a SAXParser.
    Throws:
    ParserConfigurationException - if a parser cannot be created which satisfies the requested configuration.
    SAXException - for SAX errors.
    I want to know, how to know whether a method is thread-safe?

    System.out is a PrintStream object. None of the methods there use the synchronized modifier, but if you look in the source code, you will find out it is thread-safe, because it will use synchronized blocks whenever it writes some text.
    The source code is in the src.jar file which you can extract.
    I didn't find any comments about that PrintStream is thread-safe in the API.

  • How can I get to know if a method is threads-safe?

    Hi, there.
    How can I get to know if a method is threads-safe?
    For example, in two different threads, is System.out.print() method safe or not?And where can I find the information with regard to this?
    thanks very much.

    System.out is a PrintStream object. None of the methods there use the synchronized modifier, but if you look in the source code, you will find out it is thread-safe, because it will use synchronized blocks whenever it writes some text.
    The source code is in the src.jar file which you can extract.
    I didn't find any comments about that PrintStream is thread-safe in the API.

  • How do you separate global data running in different threads of TestStand

    I have created a DLL which I want to call from multiple threads of TestStand. I also need to have some global data that is local to each thread. VC++ allows me to use the declaration:
    __declspec(thread) int foo
    to create "Thread Local Storage"
    (ie global data that is local in the each thread -- not shared between threads).
    This works fine from a VC++ application, but when I try to access data declared with this from Test Stand I get the following error.
    Win32error code 998 - Invalid access to memory location
    This occurs when I try to set a variable declared using this convention in my DllMain function.
    I get a -17502; System Level Exception when I access it from a function that I call in the DL
    L.

    Russell -
    I found the following comment in Microsoft's MSDN and I know that TestStand dynamically loads DLLs:
    If a DLL declares any nonlocal data or object as __declspec( thread ), it can cause a protection fault if dynamically loaded. After the DLL is loaded withLoadLibrary, it causes system failure whenever the code references the nonlocal __declspec( thread ) data. Because the global variable space for a thread is allocated at run time, the size of this space is based on a calculation of the requirements of the application plus the requirements of all of the DLLs that are statically linked. When you use LoadLibrary, there is no way to extend this space to allow for the thread local variables declared with __declspec( thread ). Use the TLS APIs, such as
    TlsAlloc, in your DLL to allocate TLS if the DLL might be loaded with LoadLibrary.
    Scott Richardson (NI)
    Scott Richardson
    National Instruments

  • Is the isReachable() thread safe ? How to approach it ?

    I've created a ping class which uses InetAddress.isReachable().
    I have 100 devices, with 100 threads which are using the ping object instances simultaneously.
    When one device is not reachable ( it doesn't responde), the next 5 o 10 ping test fail as well.
    I've read that isReachable is not thread safe, is this true ?
    This is the code that performes the ping.
    final long start = System.nanoTime();
    if (InetAddress.getByName(sIp).isReachable(5000)) {
    result=(System.nanoTime() - start) / 1000 / 1000;
    } else {
    result=-1;
    Thanks for your help.

    I am not sure measuring the time in seconds will be very useful unless you are trying to detect very slow response times.
    Do you investigate using broadcast pings i.e. it pings every box at once.
    Why do you have such along timeout?
    Even testing a box on the other side of the world on a decent WAN should be less than 400 ms.
    What do you mean by the next 5 to 10? Do you mean in the same thread or between theads or is it that the boxes that timeout all have the same timeout so they fail at the same time?

  • Thread safe doubt

    Hi every1
    My question:
    Multiple threads enter the method att()...i want to count how much time does attacher.attach() method takes for every thread that comes in...i think the code below works... but if i declared the timeTakenForAttach as global variable..someone told me its not thread safe...can some1 please explain me the meaning of all this OR can i declare timeTakenForAttach as global and it won't be a problem..
    class A{
      long totalAttachSetupMillis=0L;
      public void att() {
          long start = System.currentTimeMillis();
                   attacher.attach();
          long timeTakenForAttach = System.currentTimeMillis() - start;
           recordAttachSuccess (timeTakenForAttach);
       public synchronized void recordAttachSuccess(long timeForAttach){
                totalAttachSetupMillis += timeForAttach;
    }Thankyou..

    javanewbie83 wrote:
    I have to sychronize record sucess as different threads would enter att() and enter record success method and simultaneously update, so i will end up getting a wrong value.Let me give you a more detailed explanation of why NOT having it synchronized would not work.
    First of all, let's take a look at the statement of concern:
    totalAttachSetupMillis += timeForAttach;For the purposes of synchronization, however, we need to look at it like this:
    int temp = totalAttachSetupMillis + timeForAttach; //call this LINE A
    totalAttachSetupMillis = temp; //call this LINE BNow, lets say we had threads named 1 and 2. If you didn't sychronize the method, you could possibly have this execution flow:
    //initial values: totalAttachSetupMillis = 0, timeForAttack(1) = 20, timeForAttack(2) = 30.  Total should be 50
    1A //temp(1) = 0 + 20 = 20
    2A //temp(2) = 0 + 30 = 30 (remember totalAttachSetupMillis isn't set until B)
    2B //totalAttachSetupMillis = temp(2) = 30
    1B //totalAttachSetupMillis = temp(1) = 20 (instead of 50)In other words, total disaster could possibly ensue. Which is why you wanted to synchronize it. Ed's explanation of your other question was right on the money, though.

  • What does it mean to be "thread safe"?

    What does it mean to be "thread safe"?
    I am working with a team on a project here at work. Someone here suggested that we build all of our screens during the initialization of the application to save time later. During the use of the application, the screens would then be made visible or invisible.
    One of the objections to that idea was that the swing components (many of which we use) are not thread safe. Can anyone tell me what the relevance of that is?
    Thanks

    To understand why Swing is not thread safe you have to understand a little bit of history, and a little bit of how swing actually works. The history(short version) is that it is nearly impossible to make a GUI toolkit thread safe. X is thread safe(well, sorta) and it's a really big mess. So to keep things simple(and fast) Swing was developed with an event model. The swing components themselves are not thread safe, but if you always change them with an event on the event queue, you will never have a problem. Basically, there is a Thread always running with any GUI program. It's called the awt event handler. When ever an event happens, it goes on an event queue and the event handler picks them off one by one and tells the correct components about it. If you have code that you want to manipulate swing components, and you are not ON the awt thread(inside a listener trail) you must use this code.
    SwingUtilities.invokeLater( new Runnable() {
      public void run() {
        // code to manipulate swing component here
    });This method puts the defined runnable object on the event queue for the awt thread to deal with. This way changes to the components happen in order, in a thread safe way.

  • ODBC SQLGetData not thread-safe when retrieving lob

    Hi MaxDB developpers,
    we are in the process of migrating our solution from SapDb 7.4.03.32 to MaxDb 7.6.03.7. We use the ODBC driver on windows, from multi-threaded applications.
    We encountered bugs in the ODBC driver 7.4.03.32 and made our own fixes since we had the sources. I checked if these problems were fixed in 7.6.03.7 and they are allmost addressed, but one:
    when two threads use two different stmt from the same dbc and call simultaneously SQLGetData to retrieve a LONG column, a global variable not protected by a critical section is changed and the application crashes. The variable in cause is dbc_block_ptr->esqblk.sqlca.sqlrap->rasqlldp which is set by pa30bpcruntime and reset by pa30apcruntime during the call to apegetl. Calls to apegetl are protected by PA09ENTERASYNCFUNCTION except in SQLGetData, when it calls pa60MoveLongPos or pa60MoveLong.
    Since MaxDB is a critical feature of our application, we would like to know when this bug can be fixed by SAP. Or maybe could we get access to the sources of sqlod32w.dll 7.6.03.7 to fix it ourselves ?
    Thanks,
    Guillaume

    Hello Guillaume
    Regarding the threaded access to SQLGetData. Of course, it is possible to manage the syncronization as you proposed. However, I'm still not sure, whether this really solves general problems.
    The point is, that the MaxDB-ODBC driver is thread safe for concurrent connections, but not for concurrent statement processing within a single connection. Therefore I would like to ask you how your application accesses data via SQLGetData (due to connections and threads), and what amount of data is usually transfered.
    Regards  Thomas

  • BC4J View not Thread safe, user sessions are using the same view instance

    Hi There,
    We are using BC4J that came with JDeveloper 10.1.2.0.0 with Oracle 10G 10.1.2.0.0.
    I have an BC4J account search view (BC4J AccountSearchView) that users can call to search for an account. So this view could be used by numerous users and pieces of code at the same time. Now my understanding is that each user gets their own instance of the view so changing the view's query should not be an issue (since the view definition is not changing). Under a light load the account search view looks like everyone get there own instance of the view and there expected account search results. But under a heavy user load when we have User A and User B the search query that was for User A will be used by User B. So the user results for one user will get the other users results.
    I do not understand if the view definition is been changed by the other user and is impacting all view instances. How can this occur if it is thread safe?
    I have enclosed the core code for this search.
    If you can help that would be much appreciated, thanks in advance,
    Nigel
    accountSearchView.setQuery(baseSelectQuery+generateWhereClause());
    logger.debug("SearchAccounts Query: "+accountSearchView.getQuery());
    System.out.println("SearchAccounts SQL: "+accountSearchView.getQuery());
    accountSearchView.setPassivationEnabled(false);
    accountSearchView.setForwardOnly(true);
    accountSearchView.executeQuery();
    get attributes for each row result and place in new Java bean objects and return to user.

    Nigel, we've only certified JDeveloper 10.1.2 against the Struts 1.1 with which it ships.
    If there have been any changes in Struts 1.2 to the Struts Request Processor, then this could easily have an impact on the BC4JRequestProcessor's correct functioning, depending on what the changes were.
    My quick look into the issue tells me that the ActionServlet init parameter named mapping in web.xml that we use for the 9.0.3-style BC4J/Struts integration is getting ignored by Struts 1.2. This parameter is used by Struts 1.1 to globally configure a custom ActionMapping subclass which can support additional properties. My quick test shows me that Struts 1.2 is ignoring this setting and so the oracle.jbo.html.struts11.BC4JActionMapping subclass of Struts's default ActionMapping is not getting used correctly as it does in Struts 1.1. This leads to errors when Struts tries to configure its actions in struts-config.xml since the Apache digester tries to set properties on the ActionMapping instance that don't exist (since the BC4JActionMapping has these properties, and it's not being used).
      <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <init-param>
          <param-name>mapping</param-name>
          <param-value>oracle.jbo.html.struts11.BC4JActionMapping</param-value>
        </init-param>
      </servlet>This is my quick analysis of what's not out-of-the-box compatible. I don't know enough about the changes in Struts 1.2 to know why this Struts 1.1 feature broke in Struts 1.2, or what the Struts 1.2 way to accomplish the same thing is.
    I'd encourage you to use Worldwide Support's Metalink site and open a TAR for any time-critical issues you need assistance in resolving. Many of us are constantly traveling and only able to sporadically chime in with tips in the forum as our time permits.
    The source of the BC4JRequestProcessor ships with the produce in the ./BC4J/src directory inside the bc4jstrutssrc.zip file.

Maybe you are looking for

  • No: of Approvers on PO and requisition

    How can we find from backend no: of approvers that a PO or requisition have? Thanks SS

  • Errors when trying to install Service Pack 3 for Exchange 2010

    I have 2 Exchange 2010 servers that are running SP2 and I am trying to install SP3 on both. They are installed in a DAG and so I am running the .\StartDAGserverMaintenance.ps1 script before attempting to install SP3.  When attempting to run the SP3 s

  • Numerical Command-Line Arguments in Java

    Hi I am new to Java and am a little confused about setting up command-line arguments. From what I have read, the arguments are put in the args array of the main method. So accessing or using them would use args[n] right? But the args is a string arra

  • OS X 10.4.6 seems to go back a day after reboot or shutdown

    Hello my macbook is acting very weird. If i restart it seems like it didn't shutdown correctly and everything i have done is lost. EX i receve emails i have allreaddy gotten + files i create are gone... also i tried to update my os to 10.4.7 but when

  • How to remove noise from voiceover

    I am an audition CS 6 newbie.  I have tried several methods of noise reduction, but still have a noise under the voice in my voiceover.  How do I get rid of this?  I have tried adaptive noise reduction and noise reduction process. The sound is like s