AMLoginModule Thread Safety

Hello,
Ler me start by saying, we have had a lot of success with a custom login module in Access Manager paired with our custom user management system. However, recently we have come across some issues.
Within our custom login module (extends AMLoginModule) we implemented a page for resetting the user's password. This user's id and password are managed by the mentioned custom user management system. Recently we have a batch of users try to reset their passwords at the same time (30 at once), about half of them encountered errors ranging from not being able to reset their password to resetting successfully then not being able to log in with that password.
My question boils down to, does Access Manager pair the currently logging in user with the same AMLoginModule every time (much like a stateful EJB) or are the AMLoginModules pooled, thus a user can be using a login module for a while then encounter a different one (randomly) throughout the login process?
Here is the code I am dealing with:

AMLogin.java:
public class ARMLogin extends AMLoginModule  {
    private static final int SUCCESS = -1;
    private static final int DISCLAIMER = 1;
    private static final int LOGIN = 2;
    private static final int INVALIDLOGIN = 3;
    private static final int EMPTYLOGIN = 4;
    private static final int LOCKEDLOGIN = 5;
    private static final int PASSWORDRESET = 6;
    private static final int PASSWORDRESETSUCCESS = 7;
    private static final int PASSWORDRESETERROR = 8;
    private static final int PASSWORDRESETERRORSAMEOLDPW = 9;
    private static final int PASSWORDRESETERRORSAMERESTPW = 10;
    private static final String ARM_LOGIN_REMOTE_SERVICE_URL = "kcp-am-auth-armlogin-login-service-url";
     private static final String ARM_LOGIN_MODULE_LOCALE = "amAuthARMLogin";
     private Principal principal = null;
     private String wsdlUrl = null;
    private URL serviceUrl = null;
     private boolean acceptedDisclaimer = false;
     private LoginRemoteService loginServiceClient = null;
      * (non-Javadoc)
      * @see com.sun.identity.authentication.spi.AMLoginModule#getPrincipal()
     @Override
     public Principal getPrincipal() {
          return principal;
      * (non-Javadoc)
      * @see com.sun.identity.authentication.spi.AMLoginModule#init(javax.security.auth.Subject, java.util.Map, java.util.Map)
     @SuppressWarnings("unchecked")
     @Override
     public void init(Subject subject, Map sharedState, Map options) {
          //load the properties
        String serviceUri = Misc.getMapAttr(options, ARM_LOGIN_REMOTE_SERVICE_URL);
          if(serviceUri == null){
               getDebug().error("LoginService URL not specified under " + ARM_LOGIN_REMOTE_SERVICE_URL + " setting to default");
               serviceUri = ...
        try {
            serviceUrl = new URL(serviceUri);
        } catch (MalformedURLException e) {
             getDebug().error("URL Error in Service Client" , e);
        setAuthLevel(1);
        acceptedDisclaimer = false;
      * (non-Javadoc)
      * @see com.sun.identity.authentication.spi.AMLoginModule#process(javax.security.auth.callback.Callback[], int)
     @Override
     public int process(Callback[] callbacks, int state) throws LoginException {
          int processSuccess = 1;
        //disclaimer sate
        if (state == DISCLAIMER) {
            if(callbacks.length > 1 && callbacks[1] instanceof ConfirmationCallback){
                int index = ((ConfirmationCallback)callbacks[1]).getSelectedIndex();
                if(index == 0){
                    acceptedDisclaimer = true;
                    processSuccess = LOGIN;
        //username / password state
          else if (acceptedDisclaimer && (state == LOGIN || state == INVALIDLOGIN || state == EMPTYLOGIN || state == LOCKEDLOGIN || state == PASSWORDRESETSUCCESS)) {
               String username = ((NameCallback)callbacks[0]).getName();
               char[] password = ((PasswordCallback)callbacks[1]).getPassword();
               if (username == null || username.equals("") || password.length == 0){
                //empty username / password
                processSuccess = EMPTYLOGIN;
            else{
                LoginStatus status = null;
                //authorize user via web service.
                try{
                    status = getLoginRemoteService().login(username, new String(password));
                }catch(RemoteException e){
                    getDebug().error("Error in Service Client" , e);
                //if login failed restart state 2
                if(status != null){
                    if(status.getType().equals(LoginStatusType.Login.name())){
                         //success
                        principal = new LoginPrincipal(username, status.getId());
                        processSuccess = SUCCESS;
                    else if(status.getType().equals(LoginStatusType.LoginLockout.name())){
                        //locked out
                        processSuccess = LOCKEDLOGIN;
                    else if(status.getType().equals(LoginStatusType.PasswordReset.name())){
                        //success for password reset
                        principal = new LoginPrincipal(username, status.getId());
                        processSuccess = PASSWORDRESET;
                        setAuthLevel(11);
                    else{
                        //incorrect login
                        processSuccess = INVALIDLOGIN;
        else if(state == PASSWORDRESET || state == PASSWORDRESETERROR || state == PASSWORDRESETERRORSAMEOLDPW || state == PASSWORDRESETERRORSAMERESTPW){
            char[] password = ((PasswordCallback)callbacks[0]).getPassword();
            char[] passwordConfirm = ((PasswordCallback)callbacks[1]).getPassword();
            LoginPrincipal principal = (LoginPrincipal)getPrincipal();
            LoginStatus status = null;
            try{
                status = getLoginRemoteService().passwordReset(principal.getId(), new String(password), new String(passwordConfirm));
            }catch(RemoteException e){
                getDebug().error("Error in Service Client" , e);
            //if login failed restart state 2
            if(status != null){
                if(status.getType().equals(LoginStatusType.PasswordResetSuccess.name())){
                     //success
                    processSuccess = PASSWORDRESETSUCCESS;
                else if(status.getType().equals(LoginStatusType.PasswordResetErrorSameOldPW.name())){
                    //same previous password
                    processSuccess = PASSWORDRESETERRORSAMEOLDPW;
                else if(status.getType().equals(LoginStatusType.PasswordResetErrorSameResetPW.name())){
                    //same previous password
                    processSuccess = PASSWORDRESETERRORSAMERESTPW;
                else{
                    //incorrect login
                    processSuccess = PASSWORDRESETERROR;
          return processSuccess;
      * Returns the appropriate debugging logger instance
      * @return debug logger
     private Debug getDebug(){
          return Debug.getInstance(ARM_LOGIN_MODULE_LOCALE);
      * Lazily loaded LoginRemoteService
      * @return LoginRemoteService
     private synchronized LoginRemoteService getLoginRemoteService() {
          if(loginServiceClient == null){
               if(serviceUrl == null){
                    getDebug().error("LoginService URL not specified");
            try{
                LoginRemoteLocator locator = new LoginRemoteLocator();
                loginServiceClient = locator.getLoginRemoteServiceImplPort(serviceUrl);
            catch (ServiceException e){
                getDebug().error("Error in Service Client Creation" , e);
          return loginServiceClient;
}

Similar Messages

  • What are the thread safety requirements for container implementation?

    I rarely see in the TopLink documentation reference to thread safety requirements and it’s not different for container implementation.
    The default TopLink implementation for:
    - List is Vector
    - Set is HashSet
    - Collection is Vector
    - Map is HashMap
    Half of them are thread safe implementations List/Collection and the other half is not thread safe Set/Map.
    So if I choose my own implementation do I need a thread safe implementation for?
    - List ?
    - Set ?
    - Collection ?
    - Map ?
    Our application is always reading and writing via UOW. So if TopLink synchronize update on client session objects we should be safe with not thread safe implementation for any type; does TopLink synchronize update on client session objects?
    The only thing we are certain is that it is not thread safe to read client session object or read read-only UOW object if they are ever expired or ever refreshed.
    We got stack dump below in an application always reading and writing objects from UOW, so we believe that TopLink doesn’t synchronize correctly when it’s updating the client session objects.
    java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
    at java.util.AbstractList$Itr.next(AbstractList.java:420)
    at oracle.toplink.internal.queryframework.InterfaceContainerPolicy.next(InterfaceContainerPolicy.java:149)
    at oracle.toplink.internal.queryframework.ContainerPolicy.next(ContainerPolicy.java:460)
    at oracle.toplink.internal.helper.WriteLockManager.traverseRelatedLocks(WriteLockManager.java:140)
    at oracle.toplink.internal.helper.WriteLockManager.acquireLockAndRelatedLocks(WriteLockManager.java:116)
    at oracle.toplink.internal.helper.WriteLockManager.checkAndLockObject(WriteLockManager.java:349)
    at oracle.toplink.internal.helper.WriteLockManager.traverseRelatedLocks(WriteLockManager.java:144)
    at oracle.toplink.internal.helper.WriteLockManager.acquireLockAndRelatedLocks(WriteLockManager.java:116)
    at oracle.toplink.internal.helper.WriteLockManager.checkAndLockObject(WriteLockManager.java:349)
    at oracle.toplink.internal.helper.WriteLockManager.traverseRelatedLocks(WriteLockManager.java:144)
    at oracle.toplink.internal.helper.WriteLockManager.acquireLockAndRelatedLocks(WriteLockManager.java:116)
    at oracle.toplink.internal.helper.WriteLockManager.acquireLocksForClone(WriteLockManager.java:56)
    at oracle.toplink.publicinterface.UnitOfWork.cloneAndRegisterObject(UnitOfWork.java:756)
    at oracle.toplink.publicinterface.UnitOfWork.cloneAndRegisterObject(UnitOfWork.java:714)
    at oracle.toplink.internal.sessions.UnitOfWorkIdentityMapAccessor.getAndCloneCacheKeyFromParent(UnitOfWorkIdentityMapAccessor.java:153)
    at oracle.toplink.internal.sessions.UnitOfWorkIdentityMapAccessor.getFromIdentityMap(UnitOfWorkIdentityMapAccessor.java:99)
    at oracle.toplink.internal.sessions.IdentityMapAccessor.getFromIdentityMap(IdentityMapAccessor.java:265)
    at oracle.toplink.publicinterface.UnitOfWork.registerExistingObject(UnitOfWork.java:3543)
    at oracle.toplink.publicinterface.UnitOfWork.registerExistingObject(UnitOfWork.java:3503)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.registerIndividualResult(ObjectLevelReadQuery.java:1812)
    at oracle.toplink.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneNormally(ObjectBuilder.java:455)
    at oracle.toplink.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:419)
    at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:379)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:455)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.conformIndividualResult(ObjectLevelReadQuery.java:622)
    at oracle.toplink.queryframework.ReadObjectQuery.conformResult(ReadObjectQuery.java:339)
    at oracle.toplink.queryframework.ReadObjectQuery.registerResultInUnitOfWork(ReadObjectQuery.java:604)
    at oracle.toplink.queryframework.ReadObjectQuery.executeObjectLevelReadQuery(ReadObjectQuery.java:421)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:811)
    at oracle.toplink.queryframework.DatabaseQuery.execute(DatabaseQuery.java:620)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:779)
    at oracle.toplink.queryframework.ReadObjectQuery.execute(ReadObjectQuery.java:388)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:836)
    at oracle.toplink.publicinterface.UnitOfWork.internalExecuteQuery(UnitOfWork.java:2604)
    at oracle.toplink.publicinterface.Session.executeQuery(Session.java:993)
    at oracle.toplink.publicinterface.Session.executeQuery(Session.java:950)

    Hi Lionel,
    As a general rule of thumb, the ATI Rage 128 Pro will not support a 20" LCD. That being said, there are reports of it doing just that (possibly the edition that went into the cube).
    I'm not that familiar with the ins and outs of the Cube, so I can't give you authoritative information on it.
    A good place to start looking for answers is:
    http://cubeowner.com/kbase_2/
    Cheers!
    Karl

  • Vector Replacement in Java 1.4 - Is Thread Safety Needed In This Scenario?

    I have a Java 1.4 application that queries Database # 1, and builds custom strings used to create records that are inserted into Database # 2.
    Right now Vectors are used as a container to temporarily hold query output from Database # 1 while building records going into Database # 2, but I want to convert away from this legacy collection type.
    This application does this with a single "worker" thread that is started and monitored by the application main thread. If the main thread detects any exceptions, i.e. a network or any database problem, the application main thread will stop the single worker thread and restart a new single worker thread.
    There are several instances of this application running simultaneously on the same server but accessing different test databases. When put into the production environment this application will run on a separate server and there will be only 1 instance of the application running.
    I have reviewed numerous forums here and Google results and have not found much specific info that would closely apply to my exact design situation. I did not post any code since this is more of a design question than issue with a specific code snippet.
    My question is: In the scenario I described, does thread safety need to be a factor in choosing a new collection type (to replace Vectors) and in building code that accesses this new collection type?

    The several instances of the application are all independent JVMs and can't interact with each other directly at all. So there's no thread safety issue there and there never was. So what does that leave you? You've got a single worker thread using the Vector? There's no thread safety issue there either. The only time you have to think about thread safety is when two threads are trying to use the same object.

  • Urgent question about Thread-safety

    Hi all,
    the new tiger release provides an "isReachable()" method for the "InetAddress" object.
    I've found, this method is not thread-safe (see the source and output below).
    It returns true for all threads, when multiple threads using this method with different adresses are running at a time and one of the addresses is reachable. This happens only on WinXp. Running on Linux, the output is like expected.
    I've tried to report this as a bug. But the gurus answered, taking care of thread safety would be a "programmers task".
    My question is, what can I do, to be thread-safe in my case?
    W.U.
    import java.util.*;
    import java.net.*;
    public class IsReachableTest_1 extends Thread{
        static volatile int inst=1;
        static final String NET_ADDR="192.168.111.";
        int instance=inst++;
        public void run(){
            for(int i=19;i<23;i++){
                try{
                    long start=System.nanoTime();
                    if(InetAddress.getByName(NET_ADDR+i).isReachable(1000))
                        System.out.println(""+instance+"--host found at:"+NET_ADDR+i+"--time:"+(System.nanoTime()-start)/1000000);
                    else
                        System.out.println(""+instance+"--no host at:"+NET_ADDR+i);
                }catch(Exception e){System.out.println(""+instance+"--ERROR "+e.toString());}
            System.out.println(""+instance+"--done.");
        public static void main(String[] args) {
            System.out.println(
                System.getProperty("java.vendor")+" "+
                System.getProperty("java.version")+" running on "+
                System.getProperty("os.name")+" "+
                System.getProperty("os.version"));
            Vector v=new Vector();
            System.out.println("\nTest 1: One after another:");
            for(int i=0;i<10;i++){
                IsReachableTest_1 t;
                t=new IsReachableTest_1();
                t.start();
                try{
                    t.join();
                }catch(Exception e){System.out.println("MAIN1: "+e.toString());}
            System.out.println("\nTest 2: All together:");
            inst=1;
            for(int i=0;i<10;i++){
                IsReachableTest_1 t;
                t=new IsReachableTest_1();
                t.start();
                v.addElement(t);
            for(Iterator i=v.iterator();i.hasNext();)
                try{
                    ((IsReachableTest_1)i.next()).join();
                }catch(Exception e){System.out.println("MAIN2: "+e.toString());}
                System.out.println("\nALL DONE");
    And here is the output, when running on WinXp:
    Sun Microsystems Inc. 1.5.0-beta running on Windows XP 5.1
    Test 1: One after another:
    1--no host at:192.168.111.19
    1--no host at:192.168.111.20
    1--host found at:192.168.111.21--time:2
    1--no host at:192.168.111.22
    1--done.
    2--no host at:192.168.111.19
    2--no host at:192.168.111.20
    2--host found at:192.168.111.21--time:4
    2--no host at:192.168.111.22
    2--done.
    3--no host at:192.168.111.19
    3--no host at:192.168.111.20
    3--host found at:192.168.111.21--time:1
    3--no host at:192.168.111.22
    3--done.
    4--no host at:192.168.111.19
    4--no host at:192.168.111.20
    4--host found at:192.168.111.21--time:1
    4--no host at:192.168.111.22
    4--done.
    5--no host at:192.168.111.19
    5--no host at:192.168.111.20
    5--host found at:192.168.111.21--time:3
    5--no host at:192.168.111.22
    5--done.
    6--no host at:192.168.111.19
    6--no host at:192.168.111.20
    6--host found at:192.168.111.21--time:1
    6--no host at:192.168.111.22
    6--done.
    7--no host at:192.168.111.19
    7--no host at:192.168.111.20
    7--host found at:192.168.111.21--time:1
    7--no host at:192.168.111.22
    7--done.
    8--no host at:192.168.111.19
    8--no host at:192.168.111.20
    8--host found at:192.168.111.21--time:1
    8--no host at:192.168.111.22
    8--done.
    9--no host at:192.168.111.19
    9--no host at:192.168.111.20
    9--host found at:192.168.111.21--time:1
    9--no host at:192.168.111.22
    9--done.
    10--no host at:192.168.111.19
    10--no host at:192.168.111.20
    10--host found at:192.168.111.21--time:1
    10--no host at:192.168.111.22
    10--done.
    Test 2: All together:
    1--no host at:192.168.111.19
    2--no host at:192.168.111.19
    3--no host at:192.168.111.19
    4--no host at:192.168.111.19
    5--no host at:192.168.111.19
    6--no host at:192.168.111.19
    7--no host at:192.168.111.19
    8--no host at:192.168.111.19
    9--no host at:192.168.111.19
    10--no host at:192.168.111.19
    2--no host at:192.168.111.20
    3--no host at:192.168.111.20
    6--host found at:192.168.111.20--time:924 <----- this host does not exist!!
    5--host found at:192.168.111.20--time:961 <----- this host does not exist!!
    10--host found at:192.168.111.20--time:778 <----- this host does not exist!!
    9--host found at:192.168.111.20--time:815 <----- this host does not exist!!
    2--host found at:192.168.111.21--time:37
    7--host found at:192.168.111.20--time:888 <----- this host does not exist!!
    8--host found at:192.168.111.20--time:852 <----- this host does not exist!!
    4--host found at:192.168.111.20--time:997 <----- this host does not exist!!
    1--host found at:192.168.111.20--time:1107 <----- this host does not exist!!
    3--host found at:192.168.111.21--time:38
    6--host found at:192.168.111.21--time:1
    5--host found at:192.168.111.21--time:1
    10--host found at:192.168.111.21--time:2
    2--host found at:192.168.111.22--time:3 <----- this host does not exist!!
    9--host found at:192.168.111.21--time:2
    7--host found at:192.168.111.21--time:1
    4--host found at:192.168.111.21--time:3
    1--host found at:192.168.111.21--time:39
    2--done.
    1--host found at:192.168.111.22--time:5 <----- this host does not exist!!
    1--done.
    10--host found at:192.168.111.22--time:40 <----- this host does not exist!!
    3--host found at:192.168.111.22--time:192 <----- this host does not exist!!
    6--host found at:192.168.111.22--time:75 <----- this host does not exist!!
    8--host found at:192.168.111.21--time:230
    5--host found at:192.168.111.22--time:155 <----- this host does not exist!!
    4--host found at:192.168.111.22--time:78 <----- this host does not exist!!
    9--host found at:192.168.111.22--time:77 <----- this host does not exist!!
    7--host found at:192.168.111.22--time:76 <----- this host does not exist!!
    10--done.
    6--done.
    4--done.
    5--done.
    3--done.
    7--done.
    9--done.
    8--no host at:192.168.111.22
    8--done.
    ALL DONE

    I created this test (it's basically the same as your class):
    import java.util.*;
    import java.net.*;
    public class IsReachableTest_2 implements Runnable {
        private final String[] addresses = new String[] {
             "www.sun.com",
             "129.42.16.99" // www.ibm.com which is not reachable
        public void run(){
            try {
                for (int i = 0; i < addresses.length; i++) {
                    final long start = System.nanoTime();
                    final String address = addresses;
         if (InetAddress.getByName(address).isReachable(5000)) {
         System.out.println(Thread.currentThread().getName() + ": Host found at: " + address +
              " --time: " + (System.nanoTime() - start) / 1000);
         } else System.out.println("no host at: " + address);
    } catch(Exception e){
    e.printStackTrace();
    System.out.println("Thread " + Thread.currentThread().getName() + " DONE");
    public static void main(String[] args) {
    System.out.println(
         System.getProperty("java.vendor") +
         " " +
         System.getProperty("java.version") +
         " running on " +
         System.getProperty("os.name") +
         " " +
         System.getProperty("os.version")
    for (int i = 0; i < 10; i++) {
         final Thread t = new Thread(new IsReachableTest_2(), "THREAD " + (i+1));
         t.start();
    And I get:
    Sun Microsystems Inc. 1.5.0-beta running on Windows 2000 5.0
    THREAD 1: Host found at: www.sun.com --time: 217653
    THREAD 3: Host found at: www.sun.com --time: 214404
    THREAD 6: Host found at: www.sun.com --time: 214900
    THREAD 4: Host found at: www.sun.com --time: 215901
    THREAD 5: Host found at: www.sun.com --time: 216666
    THREAD 10: Host found at: www.sun.com --time: 216620
    THREAD 9: Host found at: www.sun.com --time: 217405
    THREAD 2: Host found at: www.sun.com --time: 220705
    THREAD 7: Host found at: www.sun.com --time: 220845
    THREAD 8: Host found at: www.sun.com --time: 221384
    no host at: 129.42.16.99
    Thread THREAD 4 DONE
    no host at: 129.42.16.99
    Thread THREAD 6 DONE
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    Thread THREAD 5 DONE
    Thread THREAD 10 DONE
    Thread THREAD 9 DONE
    Thread THREAD 7 DONE
    Thread THREAD 3 DONE
    Thread THREAD 1 DONE
    Thread THREAD 2 DONE
    Thread THREAD 8 DONE
    HOWEVER: I was getting some strange results every so often. Results like:
    Sun Microsystems Inc. 1.5.0-beta running on Windows 2000 5.0
    THREAD 3: Host found at: www.sun.com --time: 261132
    THREAD 9: Host found at: www.sun.com --time: 264183
    THREAD 2: Host found at: www.sun.com --time: 266447
    THREAD 6: Host found at: www.sun.com --time: 266596
    THREAD 8: Host found at: www.sun.com --time: 267192
    THREAD 5: Host found at: www.sun.com --time: 268610
    THREAD 4: Host found at: www.sun.com --time: 269849
    THREAD 1: Host found at: www.sun.com --time: 280978
    THREAD 7: Host found at: www.sun.com --time: 272589
    THREAD 10: Host found at: www.sun.com --time: 273162
    THREAD 3: Host found at: 129.42.16.99 --time: 13657
    Thread THREAD 3 DONE
    THREAD 4: Host found at: 129.42.16.99 --time: 4123
    THREAD 2: Host found at: 129.42.16.99 --time: 9439
    THREAD 5: Host found at: 129.42.16.99 --time: 6681
    THREAD 8: Host found at: 129.42.16.99 --time: 7655
    THREAD 6: Host found at: 129.42.16.99 --time: 8627
    THREAD 9: Host found at: 129.42.16.99 --time: 10586
    Thread THREAD 4 DONE
    Thread THREAD 2 DONE
    Thread THREAD 5 DONE
    Thread THREAD 8 DONE
    Thread THREAD 6 DONE
    Thread THREAD 9 DONE
    no host at: 129.42.16.99
    Thread THREAD 7 DONE
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    Thread THREAD 10 DONE
    Thread THREAD 1 DONE
    Usually the first run after I had compiled the class (!?) This isn't a thread safety problem.

  • Java Bean Thread Safety

    I've been using JavaBeans for years now, and have read at least 30 different texts and online resources about using Java beans in JSPs. But in every single one of them, they are ambiguous and non-committal about how to properly use them to avoid Thread-Safety problems in a multithreaded (web server) environment. Are there any true Java gurus out there who know how to do so in JSPs?
    Specifically, when you use the <jsp:useBean> tag, that tag automatically binds an instance of your bean to the PageContext object. Since the PageContext object is shared by many threads, wouldn't this automatically make all of the Java Bean's properties vulnerable for thread problems? Since the pageContext is shared between threads, wouldnt one have to declare every one of the bean's setters and getters as "synchronized", to prevent one thread overwriting another's values?
    I ask because in many texts, they make a vague suggestion "be sure to write your beans thread-safe"--but provide no concrete answer as to how (the level at which to declare 'synchronized'). But in all their code examples, I have never once, in all these years, seen the word "synchronized".
    How is this possible? Wouldn't the bean, as bound to the thread-shared pageContext object, be completely exposed to thread corruption, with multiple threads simultaneously calling its methods?
    Can someone supply some code snippets showing the thread-safe way to use JavaBeans (i.e., where to synchronize)

    PageContext is shared by many threads?
    Not at one time, I'm pretty certain of that.
    From the API: A PageContext instance is obtained by a JSP implementation class by calling the JspFactory.getPageContext() method, and is released by calling JspFactory.releasePageContext().
    The to me suggests the contract that a PageContext can only be in use by on one JSP page at a time. As far as I am concerned, pageContext can be treated like a "local variable" to a jsp page.
    The contents of the pageContext object are maybe a different story, but we'll get to that.
    The things to worry about with thread safety are the same as they are for servlets.
    1 - Class attributes are not threadsafe. ie variables declared within <%! %> signs
    2 - Session attributes are potentially not threadsafe if the user makes two quick requests in a row (handling two requests for the same session)
    3 - Application attributes are never threadsafe as any currently running request can access them. Most Application level attributes I treat as read only (kinda like Singleton access)
    I don't see the need to go overboard declaring everything "synchronized". In fact I think it would be hugely detrimental.

  • THREAD SAFETY ISSUE OF SERVLET

    It is possible that one instance of a sevlet is accessed by multiple
    client , then how is the concurrency issue taken care of? Especually thread safety?

    It's not, you have to handle it yourself.
    That's why it's a good idea to never put instance variables in servlets. The basic technique is to store anything you need to save between requests in the current user's session (which you get by calling request.getSession()). During a call to service() (or, more frequently, to doGet or doPost, you're safe if you use whatever is present in the request and response argument, including servlet config parameters, request parameters, request attributes, and session attributes.
    If you want to write some "real" servlet app, you should have a look at one of the frameworks, like Jakarta Struts or OpenSymphony WebWorks.

  • Thread Safety Issue with DOM

    I am parsing an XML into a DOM object using the Xerces parser that is packaged with JDK 1.5.
    First, I create a new instance of the DocumentBuilderFactory and then using the factory, create a new DocumentBuilder. I then parse the XML using the DocumentBuilder to obtain a DOM object.
    Somehow, I am seeing the same DOM object being used for different XMLs.
    Is there a thread safety issue with the Xerces parser?

    certainly, Xerces parser is not thread safe. You have to provide thread safety by making sure that only one thread is allowed to access DocumentBuilder object.

  • Reflection objects and thread safety

    Hi,
    I believe that I saw that Field and Method objects are thread-safe (i.e., can safely have methods called against a single object instance concurrently from multiple threads), but am having trouble finding such a description in the JDK javadocs static that fact.
    I'm assuming that all thread-specific 'state' would be managed by the Object target passed to methods like invoke()/get()/set() and not on the actual Field and Method objects themselves. Ideally, i'd like to only have to look up fields and methods only once reflectively, and thereafter just use the same reflection object instances to access their target objects at runtime as a performance optimizations - possibly in different threads and at the same time - without having to pay the cost of looking it up again. I should be able to do that providing Method.invoke() is thread safe. Otherwise, i'd probably be forced to call Class.getMethod() to get a new Method object to use against each object instance, which would be more costly both from a memory standpoint (more Method objects) and a lookup-cost perspective.
    Given that lots of existing performance-critical enterprise infrastructure code, such as OR database APIs, IoC frameworks and J2EE containers use reflection to decouple the generic code from any app specific code (from a compile time perspective) as an alternative to code generation, it's surprising that there's no obvious statement about thread safety in these classes. If I look at the source code for Method, it appears to be thread safe, but I can only get so far with this analysis, as the critical code in Method appears to be implemented using a class named 'sun.reflect.MethodAccessor', whose source I don't have access to.
    I know it's possible to invoke a method against multiple objects by calling Method.invoke() against each of the target objects in question. However, there's no mention as to whether it's safe to use a single Method object instance to invoke a method against multiple target object instances at the same time (i.e., from different threads running in parallel). This would fail, for instance, if the Method object had data members that were used to communicate information between internal calls without any synchronization, as the values might be used by one thread while another was changing them.
    Just to clarify (as i've seen some confusion in other forum discussions on this topic):
    I completely understand that the thread safety of a target object's method (read, small 'm') is entirely dependent upon it's implementation and not the mechanism by which it's invoked - i.e., whether a method is invoked by an explicit compiled-in call against an instance of the target object in some Java source file, or indirectly via Method object-based reflection, is immaterial the the method's thread safety.
    What i'm asking about is the thread safety of the Method.invoke() call itself (read, big 'M'). Same question wrt Field.get()/.set() as well. These calls should be thread-safe if they're stateless wrt the Method and Field object instances that they are invoked against.

    In general, if a Java API is silent about multi-threading, it is intended to be thread-safe. See the javadoc for HashMap for an example of an explicit warning.
    It is true that Java code can have bugs that show up only on unusual implementations of the Java memory model, such as relaxed memory model machines. Most (if not all) implementations of the JDK have been deployed principally on platforms with strong memory models. (Perhaps not coincidentally, those are also the machines that have market share.) There are even bugs found occasionally in the JDK core, so draw your own conclusions about the bug-tail of our software stack on systems with relaxed memory models!
    One of the more likely bugs to run into on highly optimized systems is failure of timely initialization of non-final fields in objects which are shared in an unsynchronized manner. See http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight and related pages. JDK core programmers (at Sun, to my personal knowledge) take care not to write code with such bugs, but application programmers might.
    And, yes, caching your own Method objects is a good idea, if only because their lookup is generally cumbersome and slow. If you are very performance sensitive, you'll end up generating bytecode "shim" between your callers and the desired target methods. I expect that the http://openjdk.java.net/projects/mlvm/ (an openjdk project we are just starting) will provide some relief for this; stay tuned.
    Finally, since Method objects have no state to speak of (except their "accessible" bit, which is an ahead-of-time configuration), it would be really, really surprising if they could create a race condition of some sort. If you expect race conditions in formally stateless data structures, you are certifiably paranoid. (A normal state on some platforms, hopefully not on Java.)
    For more information about method calls, including reflective methods, see my blog post: http://blogs.sun.com/jrose/entry/anatomy_of_a_call_site
    Best wishes...

  • Please Explain SRV.2.3.3.3 Thread Safety

    SRV.2.3.3.3 Thread Safety
    Implementations of the request and response objects are not guaranteed
    to be thread safe. This means that they should only be used within the
    scope of the request handling thread. References to the request and
    response objects must not be given to objects executing in other
    threads as the resulting behavior may be nondeterministic.
    My question is does a scenario arise often in practice? And if so,
    could you let me know when.Basically what precautions should I take regarding this clause.

    My question is does a scenario arise often in practice?No, because people are usually smart enough not to access request and response objects from several threads :-)
    And if so, could you let me know when.If you access request and response objects from other threads.
    Basically what precautions should I take regarding this clause.Don't access request and response objects from other threads. Don't store them in any static variable, or store them in some data structure where they can end up being accessed from random places.
    As much as possible, access request and response only in the servlet. That is smart anyway: you don't want to pass them to your "business code" because that makes the business code less reusable and harder to test.
    Usually this pretty much takes care of itself. There is rarely need to store the objects anywhere. One trap is declaring fields in servlets and storing something there. Never have fields in servlets, it is a bad idea because it is usually thread unsafe (except static final constants).

  • What is the result of violating the thread safety rule of Swing?

    I needs to know what is the outcome of violating the thread safety rule of swing? memory leak? I have seen code violating the rule but still runs fine. Did anyone know?
    Thanks

    I had violated this rule and sometime it flies and sometimes it does a crash and burn. Most often it can result in a bug seen so rarely that it does not become a concern until the day of product roll-out. Mostly it can result in intermitent GUI anomallies and sometimes total app locks that are hard to intentionally reproduce. All paints and updates are done on the event queue and it is possible to invoke a thread on it saftly.
    I refer you to the tutorial at: http://java.sun.com/docs/books/tutorial/uiswing/mini/threads.html

  • Query on thread safety

    Hi everybody
    i have a query relating to thread safety.When we say that Vector is thread safe or synchronized and Arraylist is not synchronized,what does that really mean.if possible can you provide me with a piece of code to clear the above query.
    Also can you tell me in which situations i should use a Vector & Arraylist in my code.
    regards
    kvikram

    i have a query relating to thread safety.When we say
    that Vector is thread safe or synchronized and
    Arraylist is not synchronized,what does that really
    mean.You have two or more theads accessing data. At least one of those is modifying the data. That is the problem.
    >
    Also can you tell me in which situations i should use
    a Vector & Arraylist in my code.You create your code in the context in which it exists.
    If you are using threads then the data that is accessible to more than one thread must be thread safe it that is a problem. Vector and ArrayList are classes and not solutions to that problem.

  • Thread safety in FMIS

    Can two threads access the same variable in an FMIS application?
    I'm collecting a queue (associative array) of values submitted by clients in an FMS App, and using setInterval to call a function which collects the queue at 10-second intervals, reads the values in the array, and sends them to a remote web service. I'm concerned that the first process might be trying to update the queue while the second is trying to use it.
    Everywhere I read that FMS apps are single threaded, but I've had some odd results at the web service which seem to indicate lost data. If there is a potential thread safety issue, could it be prevented by wrapping the queue in a sharedObject?

    The implementation is a bit more complex then this. When you create a JCD that implements an existing web service (ie a JCD that is started by a connector), eDesigner will create a message driven bean that is triggered by the connector and a stateless session bean that will be called from the message driven bean. This stateless session bean will call your JCD web service method, the receive or the start method.
    Because your JCD is hosted in a stateless session bean it will receive all the benefits of the J2EE thread and instance management. If there are multiple JMS messages to process, the application server can create multiple instances of the stateless session bean that hosts your JCd and thereby multiple instances of your JCD class will be created. If these are no longer needed, the application server can destroy them. As stateless session beans are thread safe, you do not need to code your JCD's in a thread safe manner. Of course if you want to access static resources or use singletons then you will need to access these in a threda safe manner from the JCD.
    When you JCD's are started by a JMS message (this is when your JCD's implement the JMS receive web service), you can configure in the connectivity map how many instances of your JCD can be started concurrently by the application server. When double clicking the configuration block on the JMS inbound connection you can specify two options:
    - Connection Consumer or Serial mode: multiple instances can be started when multiple messages are available or not.
    - Server session pool size: how many instances can be created.

  • MessageFormat.format - Thread safety - vital question

    Hello Forum
    This question is especially on the function *"public static String format(String pattern, Object... arguments)"* in Message format class. No information is given in Javadoc for this function regarding thread safety. However a generic message for the entire class is given in the javadoc stating that the - *"Message formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally."*
    It is for this reason I believe the code scanning tools like Fortify catch this function as having lack of thread safety for web applications.
    However, if you look at the decompiled source of the function - no shared object is being accessed. The decompiled source of this function is below -
    +public static String format(String pattern, Object ... arguments) {+
    MessageFormat temp = new MessageFormat(pattern);
    return temp.format(arguments);
    +}+
    Here no shared object is being accessed, a new object is created within the static method and the same is used for formatting. This decompiled version indicates that this method is actually thread safe (since no shared object is present and each method stack in each thread will have its own copy of MessageFormat. No sharing happens).
    Could you tell us if this is the case in the current scenario. This particular format method is actually thread safe when compared to other format methods.
    regards
    Phani Lanka

    user10855645 wrote:
    Hello Forum
    This question is especially on the function *"public static String format(String pattern, Object... arguments)"* in Message format class. No information is given in Javadoc for this function regarding thread safety. However a generic message for the entire class is given in the javadoc stating that the - *"Message formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally."*Doesn't sound like much of a question. They're not threadsafe, so use separate instances for separate threads, or use appropriate synchronization. Open and shut.
    However, if you look at the decompiled source of the function......you're doing it wrong. The implementation is the wrong place to look, and you can't rely on that. Go by the documentation, not by the implementation.
    And you're confused as well. The docs for that method say: "Creates a MessageFormat..." So you have your answer right there.
    Here no shared object is being accessed, a new object is created within the static method and the same is used for formatting. This decompiled version indicates that this method is actually thread safeWrong. The documentation indicates that it's threadsafe. The deompiled code only tell you what that particular implementation is doing.
    I'm not sure what you're concerned or confused about in the first place. The docs for the class say "use a separate instance for each thread," and the docs for that method say, "creates a new instance." So where's the confusion?

  • Dumb question about Thread Safety in Servlets

    Hi all
    I wrote this Client API for sending requests and receiving responses to / from a multivalue database. The API is called by my Servlet. Now it seems my API is not thread safe because when several people open up the servlet at the same time, the API gets totally confused. When the API calls are inside a synchronized(){} it works just fine, but obviously at a big performance hit. Is that the wrong way of doing it??
    However when I was doing the ACID test locally on my machine, by opening two command prompts and excuting the same java program (with the same code in it as the servlet, but standalone) my API worked just fine. How come?
    Any insights appreciated as I am just learning about thread safety now (the hard way :-( )
    cheers
    Dejan

    Does this help
    Are you using one connection to the database shared by all instances
    of your servlet
    And is this connection create in the init method of the servlet and stored
    in the servlet context.
    Problem 4 people try and use your servlet at the same time, each servlet trys to
    create a connection to the database and then store it in the servlet context and
    this causes a problem.
    Solution create a listener to create the connection and store it in the servlet context
    when the servlet is created.
    If this is your problem it is not advisable to use only one connection to the db
    try using db pooling

  • Thread safety! Is this the right way?

    Hello,
    Lately I'm reading lot about thread-safety in Swing...
    so just wondering that is this the right way to code ...
    For ex following code executes(which makes DB connection and load some list) when user press the "connect (JButton)" ....
    private void prepareAndShowConnBox()
            //System.out.println("prep - EDT: " + javax.swing.SwingUtilities.isEventDispatchThread());
            pwd.setEchoChar('*');
            javax.swing.Box box1 = new javax.swing.Box(javax.swing.BoxLayout.Y_AXIS);
            javax.swing.Box box2 = new javax.swing.Box(javax.swing.BoxLayout.Y_AXIS);
            box1.add(new javax.swing.JLabel("DB URL :     "));
            box2.add(db_url);
            box1.add(new javax.swing.JLabel("User Name :  "));
            box2.add(uid);
            box1.add(new javax.swing.JLabel("Password :   "));
            box2.add(pwd);
            final javax.swing.Box box = new javax.swing.Box(javax.swing.BoxLayout.X_AXIS);
            box.add(box1);
            box.add(box2);
            int retval = javax.swing.JOptionPane.showOptionDialog(me, box,
                    "Database Connection:",
                    javax.swing.JOptionPane.OK_CANCEL_OPTION,
                    javax.swing.JOptionPane.QUESTION_MESSAGE,
                    null, null, null);
            if(retval == javax.swing.JOptionPane.OK_OPTION)
                status.setText("Connecting...");
                Thread t = new Thread(makeConn, "Conn Thread");
                t.setPriority(Thread.NORM_PRIORITY);
                t.start();
        }And the makeConn is....
    private Runnable makeConn = new Runnable()
            boolean success;
            Exception x;
            public void run()
                //System.out.println("Con - EDT: " + javax.swing.SwingUtilities.isEventDispatchThread());
                success = true;
                x = null;
                try
                    //load sun JDBC-ODBC bridgr driver...
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    //make connection to DB...
                    con = java.sql.DriverManager.getConnection("jdbc:odbc:" + db_url.getText(),
                            uid.getText(), new String(pwd.getPassword()));
                catch(Exception e)
                    success = false;
                    x = e;
                    System.err.println(x);
                java.awt.EventQueue.invokeLater(GUItask);
            Runnable GUItask = new Runnable()
                public void run()
                    //System.out.println("Con gui - EDT: " + javax.swing.SwingUtilities.isEventDispatchThread());
                    if(success)
                        bConn.setText("Disconnect");
                        status.setText("");
                        status.setIcon(imgLink);
                        imgLink.setImageObserver(status);
                        //load the pic list...
                        Thread t = new Thread(execQuery, "List1 Thread");
                        t.setPriority(Thread.NORM_PRIORITY);
                        t.start();
                    else
                        status.setText("Connection Failed.");
                        showErr(x.toString());
        };Here uid,db_url (JTextField) , pwd (JPasswordField) , status (JLabel) are class fields.
    Thanks for any comments... :)

    Threading looks fine too me... the connection is created on a background thread, but (critically) all GUI updates are performed on the EDT, even if there's an exception. Well done.
    My only comment is... why is your GUI creating a database connection at all? Ideally the controler would get the DAO (which would connect itself) and inject it (the connected DAO) into the view... but I'm a server-side boy, so feel free to ignore me.
    Cheers. Keith.

Maybe you are looking for

  • How do I change the photo of myself that is being placed on my outgoing emails?

    I just realized that Safari is attaching a test photo of me to each of my outgoing email, mostly job applications. I'm sitting there with morning hair, a t-shirt and 5 oclock shadow. I searched everywhere looking for a way to either change or remove

  • External Hard Drives Changing Permissions to Read Only

    Three of my USB external hard drives have suddenly changed to read only. One of the times I was trying to transfer/back-up the files from one drive that had changed to read only to another external. Suddenly the second drive changed permissions. Then

  • How to stream IMAC to my TV?

    I just purchased Apple TV set it up.   I updated iTUNEs and my Apple TV software and I am able to view my iTUNES library on my TV.  However, I cannot stream from my IMAC to the Apple TV.  Is there a minimum revision of IMAC needed?  Or are there spec

  • How to implement optemistic locking in pl/sql for oracle database

    i have search the net to find example of how i can do the optimistic locking in pl/sql, all the resources i found were old , for example "Optimistic Locking with Concurrence in Oracle. As " by Graham Thornton Snr. Database Architect / Oracle DBA in 2

  • OBIEE 11g - Navigation from Hierarchy Column

    Hi Experts, I have created one Organization Hierarchy (Country --> Region --> State --> City) in the Logical Layer of the rpd and pull that hierarchy with the dimension in the Presentation Layer. In the new analysis I have created dashboard prompt wi