[WLS92] Thread synchronization bottleneck in RJVMManager

All,
First off, apologies for the long post -- there is a lot to get through.
h3. Environment:
Weblogic Server 9.2 MP3 deployed into Solaris 10 / Sparc hosts.
Sun JDK 1.5.0_12 JVM (shipped with WLS)
h3. Problem:
We are experiencing a problem with out WLS 9.2/MP3 (Solaris/Sparc) installation. We have a number of servers each running the same WLS configuration but some with different application: one server is running App A, 4 other servers are running App B (not in a cluster). We are using JMS to transfer messages from App A to App B in a strict failover configuration such that App A will always try and send to App B1, App B2, AppB3 and finally App B4, moving from one to the next if the transfer fails or takes longer than a given timeout (10 seconds). The dispatching happens in separate threads, which I will refer to as 'senders', so we can timeout the transfer attempt.
In the 'happy day' scenario where all four App B servers are up and running, everything works as expected.
Problems start to surface when we test the failover configurations.
In scenarios where the hosts are available but WLS is in either not running or in Admin mode, the failover proceeds as expected.
In scenarios where the hosts are unavailable (hardware is powered down, network is disrupted etc.), the failover does not proceed as expected. In a scenario where App B1 is down but the other three are available for example, the following are observed:
1. the time taken for the underlying socket connection to App B1 to timeout is very long (~7.5 minutes).
2. the connections to the other hosts appear to block until after the socket timeout to App B1 occurs.
The relevant section of the code is:
weblogic.security.Security.runAs(new Subject(), new PrivilegedAction<Void>() {
     public Void run() {
          InitialContext context = null;
          try {
               * During server-to-server sending of messages we must establish and maintain
               * a new context that will contain the security information established by
               * the initial context object. This has to be done per thread, hence why it
               * is applied here to the dispatcher. The context will be closed when
               * the thread is returned.
               final Hashtable<?,?> environment = getEnvironment();
               try {
                    if (log.isDebugEnabled()) {
                         log.debug(format("run(): Sender %d Creating initial context; env=%s", id, environment));
                    context = new InitialContext(environment);
                    if (log.isDebugEnabled()) {
                         log.debug(format("run(): Sender %d Created initial context in %d ms", id, System.currentTimeMillis() - start));
                    runWithContext();
               } catch (NamingException e) {
                    log.error(format("run(): Sender %d cannot create initial context", id), e);
          } finally {
               try {                           
                    if (context != null) {
                         if (log.isDebugEnabled()) {
                              log.debug(format("run(): Sender %d closing initial context", id, context));
                         context.close();
               } catch (NamingException e) {
                    log.error(format("run(): Sender %d cannot close initial context", id), e);
          return null;
Thread stacks for two sample threads in this scenario are as follows. Thread '20' is the sender attempting to connect to App B1, Thread '8' is the sender attempting to connect to App B2 and is representative of a number of other threads all attempting to connect to known good hosts.
Daemon Thread [[ACTIVE] ExecuteThread: '20' for queue: 'weblogic.kernel.Default (self-tuning)'] (Suspended)     
     PlainSocketImpl.socketConnect(InetAddress, int, int) line: not available [native method]     
     SocksSocketImpl(PlainSocketImpl).doConnect(InetAddress, int, int) line: 333     
     SocksSocketImpl(PlainSocketImpl).connectToAddress(InetAddress, int, int) line: 195     
     SocksSocketImpl(PlainSocketImpl).connect(SocketAddress, int) line: 182     
     SocksSocketImpl.connect(SocketAddress, int) line: 366     
     SSLSocketImpl(Socket).connect(SocketAddress, int) line: 519     
     SSLSocketImpl(Socket).connect(SocketAddress) line: 469     
     SSLSocketImpl(Socket).<init>(SocketAddress, SocketAddress, boolean) line: 366     
     SSLSocketImpl(Socket).<init>(InetAddress, int, InetAddress, int) line: 266     
     SSLSocketImpl(SSLSocket).<init>(InetAddress, int, InetAddress, int) line: 195     
     SSLSocketImpl.<init>(TLSSystem, InetAddress, int, InetAddress, int) line: not available     
     SSLSocketFactoryImpl.createSocket(InetAddress, int, InetAddress, int) line: not available     
     ChannelSSLSocketFactory.createSocket(InetAddress, int) line: 77     
     MuxableSocketT3S(AbstractMuxableSocket).createSocket(InetAddress, int, int) line: 207     
     MuxableSocketT3S(MuxableSocketT3).newSocketWithRetry(InetAddress, int, int) line: 252     
     MuxableSocketT3S(MuxableSocketT3).connect(InetAddress, int, int) line: 421     
     MuxableSocketT3S.createConnection(InetAddress, int, ServerChannel, JVMID, int) line: 79     
     ConnectionManager.createConnection(Protocol, InetAddress, int, ServerChannel, JVMID, int) line: 1749     
     ConnectionManagerServer(ConnectionManager).findOrCreateConnection(ServerChannel, JVMID, int) line: 1410     
     ConnectionManagerServer(ConnectionManager).bootstrap(JVMID, ServerChannel, int) line: 448     
     ConnectionManagerServer(ConnectionManager).bootstrap(InetAddress, int, ServerChannel, int) line: 326     
     RJVMManager.findOrCreateRemoteInternal(InetAddress, int, String, String, int) line: 261     
     RJVMManager.findOrCreate(InetAddress, int, String, String, int) line: 204     
     RJVMFinder.findOrCreateRemoteServer(InetAddress, int, String, int) line: 226     
     RJVMFinder.findOrCreate(boolean, String, HostID, int) line: 189     
     ServerURL.findOrCreateRJVM(boolean, String, HostID, int) line: 154     
     WLInitialContextFactoryDelegate$1.run() line: 342     
     AuthenticatedSubject.doAs(AbstractSubject, PrivilegedExceptionAction) line: 363     
     SecurityManager.runAs(AuthenticatedSubject, AuthenticatedSubject, PrivilegedExceptionAction) line: 147     
     WLInitialContextFactoryDelegate.getInitialContext(Environment, String, HostID) line: 337     
     Environment.getContext(String, HostID) line: 307     
     Environment.getContext(String) line: 277     
     WLInitialContextFactory.getInitialContext(Hashtable) line: 117     
     NamingManager.getInitialContext(Hashtable<?,?>) line: 667     
     InitialContext.getDefaultInitCtx() line: 247     
     InitialContext.init(Hashtable<?,?>) line: 223     
     InitialContext.<init>(Hashtable<?,?>) line: 197     
     FailoverMessageSender$Sender$1.run() line: 475     
     FailoverMessageSender$Sender$1.run() line: 458     
     AuthenticatedSubject.doAs(AbstractSubject, PrivilegedAction) line: 321     
     SecurityManager.runAs(AuthenticatedSubject, AuthenticatedSubject, PrivilegedAction) line: 121     
     Security.runAs(Subject, PrivilegedAction) line: 41     
     FailoverMessageSender$Sender.run() line: 457     
     DelegatingWork.run() line: 61     
     J2EEWorkManager$WorkWithListener.run() line: 259     
     ExecuteThread.execute(Runnable) line: 209     
     ExecuteThread.run() line: 181     
Daemon Thread [[ACTIVE] ExecuteThread: '8' for queue: 'weblogic.kernel.Default (self-tuning)'] (Suspended)     
     RJVMManager.findOrCreateRemoteInternal(InetAddress, int, String, String, int) line: 252     
     RJVMManager.findOrCreate(InetAddress, int, String, String, int) line: 204     
     RJVMFinder.findOrCreateRemoteServer(InetAddress, int, String, int) line: 226     
     RJVMFinder.findOrCreate(boolean, String, HostID, int) line: 189     
     ServerURL.findOrCreateRJVM(boolean, String, HostID, int) line: 154     
     WLInitialContextFactoryDelegate$1.run() line: 342     
     AuthenticatedSubject.doAs(AbstractSubject, PrivilegedExceptionAction) line: 363     
     SecurityManager.runAs(AuthenticatedSubject, AuthenticatedSubject, PrivilegedExceptionAction) line: 147     
     WLInitialContextFactoryDelegate.getInitialContext(Environment, String, HostID) line: 337     
     Environment.getContext(String, HostID) line: 307     
     Environment.getContext(String) line: 277     
     WLInitialContextFactory.getInitialContext(Hashtable) line: 117     
     NamingManager.getInitialContext(Hashtable<?,?>) line: 667     
     InitialContext.getDefaultInitCtx() line: 247     
     InitialContext.init(Hashtable<?,?>) line: 223     
     InitialContext.<init>(Hashtable<?,?>) line: 197     
     FailoverMessageSender$Sender$1.run() line: 475     
     FailoverMessageSender$Sender$1.run() line: 458     
     AuthenticatedSubject.doAs(AbstractSubject, PrivilegedAction) line: 321     
     SecurityManager.runAs(AuthenticatedSubject, AuthenticatedSubject, PrivilegedAction) line: 121     
     Security.runAs(Subject, PrivilegedAction) line: 41     
     FailoverMessageSender$Sender.run() line: 457     
     DelegatingWork.run() line: 61     
     J2EEWorkManager$WorkWithListener.run() line: 259     
     ExecuteThread.execute(Runnable) line: 209     
     ExecuteThread.run() line: 181     
h3. Conclusion:
All of the threads are jamming up in RJVMManager.findOrCreateRemoteInternal(..) behind the one thread that is actually attempting to make a connection.
A quick disassemby of the offending method class shows the following snippet:
/* */ private RJVM findOrCreateRemoteInternal(InetAddress paramInetAddress, int paramInt1, String paramString1, String paramString2, int paramInt2)
/* */ throws UnrecoverableConnectException, IOException
/* 246 */ RJVM localRJVM = findExisting(paramInetAddress, paramInt1, (ServerChannel)localObject1);
/* 248 */ if (localRJVM != null) return localRJVM;
/* 250 */ synchronized (this.bootstrapLock)
/* 252 */ localRJVM = findExisting(paramInetAddress, paramInt1, (ServerChannel)localObject1);
/* 253 */ if (localRJVM != null) return localRJVM;
/* 256 */ if ((Kernel.DEBUG) && (debugConnection.isDebugEnabled())) {
/* 257 */ RJVMLogger.logDebug("Bootstrapping connection to: '" + paramInetAddress + ":" + paramInt1 + "' using: '" + localProtocol + "'");
/* 260 */ ConnectionManager localConnectionManager = ConnectionManager.create(null);
/* 261 */ return record(localConnectionManager.bootstrap(paramInetAddress, paramInt1, (ServerChannel)localObject1, paramInt2), paramInetAddress);
Now the problem becomes clear. I suspect that the reason for the synchronized block on line 250 is to prevent two threads attempting the relatively expensive operation on line 261 (see lines 248-250 and 252-253). However, the flaw here is that the synchronization blocks all threads irrespective of which InetAddress (param 1) the thread is attempting to connect to. My personal opinion is that the monitor used for thread synchronization should be timed to the host (InetAddress) for the connection, which incidentally is used in the record(..) method anyway.
The problem is exacerbated by the very long network connection timeout.
h3. Solutions:
We've tried setting the sun.net.defaultConnectTimeout JVM property to try and reduce the impact but haven't seen any noticeable improvement.
We've tried specifying the weblogic.jndi.clientTimeout and weblogic.jndi.requestTimeout values when creating the InitialContext. For some reason specifying these properties caused all connection attempts to fail -- even the happy day scenarios.
h3. Final Questions:
Is this a bug? If so, what do I need to do to get this fixed urgently?
Is this a bug other people have run into? If so, how was it resolved?
Any other suggestions?
Thanks!
Edited by: user11373704 on 10-Jul-2009 08:52

Perhaps the relevant timeouts are socket/network related in this case.
To detect "silent" network failures, WebLogic uses a heartbeat mechanism, but I'm told that one should not tune the related settings too aggressively. I think this is tunable on a per server basis -- at least for the default network channels. Specifically there's heartbeat interval and period length on the console at "Server -> Configuration Tab --> Tuning Tab --> Advanced".
There's also "Complete Message Timeout" under "Protocol -> General".
In addition, TCP/IP timeouts are tunable on the operating system itself. I don't know the specifics for Solaris.
Tom

Similar Messages

  • Need help for thread synchronization

    Hi guys,
    i got some problem with the thread synchronization.
    actually my code is like,
    class myClass
    public static void main()
    PvsIdentify identifyThread = new PvsIdentify(this); //Child trd 1
    PvsPolling pollingThread = new PvsPolling(this); //Child trd 2
    identifyThread.start();
    pollingThread.start();
    synchronized(this) {
    try {
    this.wait();
    } catch (Exception ex) {
    ex.printStackTrace();
    /// Code to follow based on the ouput from these two child threads
    if( ! identifyThread.getOutput() =="")
    my requirement is ,
    the identifyThread is giving an output. so after the completion of that child thread only IF condition should execute.
    but for me the IF condition is getting execute before the complete execution of identifyThread.
    what may be the problem.
    thanx in advance.---------------Subbu

    my problem is, that child thread identifyThread will do some process and final throw the output in a JOption dialog box to the main window.
    if we use join for the child thread then that dialog box will not come the the main window.
    This is my code,
              businessCancel = false;
              pollingCancel = false;
              String userName = txtInputId.getText();
                    //CHECK FOR EXISTANCE OF USER NAME
                    boolean isNameExist=false;
                    int isString = this.isValidName(userName);
                    try { // This code block invokes the PalmsSEIPort:isNameExist operation on web service
                        palmsecuresdk.sample.Palms palms = new palmsecuresdk.sample.Palms_Impl();
                        palmsecuresdk.sample.PalmsSEI _palmsSEIPort = palms.getPalmsSEIPort();
                        isNameExist = _palmsSEIPort.isNameExist(userName);
                        System.out.println("The result of isNameExist is==="+isNameExist);
                    } catch(javax.xml.rpc.ServiceException ex) {
                        // TODO handle ServiceException
                    } catch(java.rmi.RemoteException ex) {
                        // TODO handle remote exception
                    } catch(Exception ex) {
                        // TODO handle custom exceptions here
                    if(isNameExist==false)
                        if (isString==1) {
                            // CHECK FOR EXISTANCE OF USER PALM DATA
                            //Identify process
                            setComponentEnabled(false);
                            PvsIdentify identifyThread = new PvsIdentify(this);
                            PvsPolling pollingThread = new PvsPolling(this);
                            identifyThread.start();  
                            pollingThread.start();
                            btnCancel.requestFocus();
                            synchronized(this) {
                                    try {
                                        System.out.println("the owner of this thread is "+this.getOwner());
                                         identifyThread.join();
                                         pollingThread.join();
                                        System.out.println("Main thread is sleeping now");
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                            this.notifyAll();
                            System.out.println("After the identify process over");
                            String isPalmExist = identifyThread.getFinalResult();
                            while(isPalmExist.equals(""))
                                isPalmExist = identifyThread.getFinalResult();
                                if(!isPalmExist.equals(""))
                                    this.notifyAll();
                            System.out.println("The identify result is "+isPalmExist);
                            if(isPalmExist.equalsIgnoreCase("Identify Failed"))
                                // To display PROCEED MsgBox
                                identifyThread.result=102;
                                identifyThread.resultNotify(isPalmExist);                           
                                // Execute enrollment process.
                                setComponentEnabled(false);
                                PvsEnroll enrollThread = new PvsEnroll(this, this, userName);
                                //PvsPolling pollingThread = new PvsPolling(this);
                                enrollThread.start();
                                pollingThread.start();
                                btnCancel.requestFocus();                           
                            else
                                identifyThread.result=101;
                                identifyThread.resultNotify(isPalmExist);
                        else {
                                // Guidance display(ID is not correct.)
                                String message = langFileAccessor.getLangInfo(
                                                                        PvsLangFileAccessor.KEY_GUIDANCE_ILLEGALID);
                                dispGuidance(message);
                                initState();
                    else
                        String message = langFileAccessor.getLangInfo(PvsLangFileAccessor.KEY_GUIDANCE_EXISTINGID);
                        dispGuidance(message);
                        initState();
                    }

  • Thread Synchronization problem

    We guys are developing a P2P file sharing software(on LAN) and our program requires that we implement a multi-threaded client. I somewhere read on the forum about a multi threaded server but it doesnt work in my case (not on the client side.)The program runs properly when a single transfer is happening but if more then one file is getting downloaded the program seems to fall apart. Here's the code that provides the client side implementation of a file transfer.
    class Down implements Runnable     
                         DataOutputStream dataOutput;     
                         BufferedInputStream bufferedInput;     
                         FileOutputStream fileOutput;
                         Socket down;
                         public void run()
                                      try
                                              int data=0;
                                              long i=0;
                                              down=new Socket(user,9999);
                                              dataOutput=new DataOutputStream(down.getOutputStream());  //The following two lines send the file path to the server, to make the server's job easier rather than the server going for a file search
                                              String msg=path.replace('\\','/');   dataOutput.writeUTF(msg);     
                                              dataOutput.flush();
                                              bufferedInput=new BufferedInputStream(down.getInputStream());
                                              fileOutput=new FileOutputStream(new File(path));
                                              while (data != -1)
                                                       data=bufferedInput.read();
                                                       fileOutput.write(data);
                                                       fileOutput.flush();
                                                       i++;
                                                       System.out.println("Transferring "+i);
                                              System.out.println("File Transfer Done");
                                              done=true;
                                     catch (Exception e)
                                                 e.printStackTrace();
                                     } Can you guys point out specifically where my program would need synchronization, since im a noob when it comes to threads. Thanks

    Thanks ejp for those prompt replies .......yeah the path and the down socket) variables are unique...... from what i see on my network .... the server side of the transfer happens at a faster rate i.e the final println line printing the transferred byte (at the end of the while loop) is much ahead at the server side of the transfer ...... the client lags far behind in this regard...... and from what i know Lan connections support upto 100Mbps so there's no question of data loss..... one of the reasons i opted for byte by byte transfer....... just to be on the safer side...... and yes ill make that small change in my program

  • Struts Action threading model bottleneck

    Hi,
    Struts Action classes are only instantiated once. Then the controller servlet routes all perform/execute calls through the single instantiated Action class. Does this create a performance bottleneck? Any insights would be helpful.
    Thanks

    It's more performant, since it doesn't need to create new objects for each request. You just need to write your code in a thread-safe manner (watch the instance variable!).
    Cheers

  • Thread synchronize with GUI controls

    I need to modify some GUI controls (append text to JTextArea) from my custom thread..
    Javadoc say that the method append of JTextArea is thread-safe, but if I call it from my thread the application go in blocking-state
    So I try to use, SwingUtilities.invokeLater but when I try to append some text to JTextArea, the application go in blocking-state..
    How can I do for synchronize method call from my thread to main thread..?
    Thanks..

    This is my code:
    private void WriteDebugSafe(final String str)
              Runnable WriteText = new Runnable()
         public void run()
         debug.append(str+"\n");          
         SwingUtilities.invokeLater(WriteText);                    
    After the call to invokeLater.. the application go in blocking-state.
    This appened sometimes.. NOT systematically..

  • Java Two Threads Synchronization Problem

    Hello to all, i have a scenario like this where a manager open a restaurant which signal the arrival of customer.
    Each entity here is one thread.
    How to signal the customer from manager that is open state ?
    I have a boolean variable (IsOpen) in manager class.
    My code:
    public class Manager implements Runnable {
         boolean IsOpen, IsStartWorking, IsLastOrder,
              IsClosingTime;
         public void run()
             try
                  // while not closing time
                  while (true)
                       if (!IsOpen && !IsStartWorking)
                            open();
                            startWorking();
                       prepareCappuccino();
                       prepareHotChocolate();
                       prepareFruitJuice();
                       // serve drink then refill Ingredients based on
                       // order
                       myCoffeePowder.refillCoffeePowder();
                       myCocoPowder.refillCocoPowder();
                       myMilk.refillMilk();
                       myFJ.refillFruitJuice();
                       Thread.sleep(100);
                  // Manager alert closing time
                  //closingtime();
                   //sanityCheck();
                   //statisticsDispaly();
                   //managerLeave();           
             catch(InterruptedException e)
                  e.printStackTrace();
              public void open() {
             IsOpen = true;
              System.out.println(dateFormat.format(cal.getTime()) +
                   " Thread Manager: Manager open Restaurant");
              //notifyAll();
    }I want to notify the customer thread when the IsOpen state become true.
    As you can see from open() method, there is notifyAll() but it turn error because it does not own the monitor.
    I have solution like this create a monitor with Isopen variable and once is open notifyAll().
    I never tried that.
    Please give some comment.
    The logic here is model using FSP like below
    MANAGER = (manager.open->startWorking->STARTWORKING),
    CUSTOMER = (manager.open->CUST_ARRIVE),manager.open is a shared action in FSP.
    Please help.
    Thanks.

    I think you had taken notify and notifyall in not correct way. According to me you need a another class say HotelManagement which hold the information of state of Manager and customer. This will hold the list of customer which are requsting to be allowed in hotel.So this class has methods like (Please pardon me for choosing some bad names ..I hope you will find some better names).
    1. updateStateOfManager() = which allow manager to Update its state. and if state become open it will take each customer from RequsetedCustomer list and call their allowed method. If state become Closed it will take each customer from RequsetedCustomer list and call their removed method.
    2. requestfromCustomer()= this method called by customer requesting for entry in hotel. if the state is open it allowed them immediately and kept in RequestedCustomer list too so that they can be removed when manager state changed. and if manager state is closed they are not allowed but kept in RequsetedCustomer list.
    3. finshedFromCustomer()= customer done in hotel so remove from RequsetedCustomer list;
    You can used AtomicBoolean objects for keeping state of Manager other thread safe data Structure for holding other objects.

  • Question on Thread synchronization

    Why the use of synchronized key word doesnt guarantee sequential
    execution of the code across multiple threads , unless we use wait and
    Notify ?

    The question is non-sensical - if you want sequential execution then there absolutely no point in using multiple threads in the first place.

  • How to handle Thread synchronization

    Hi guys,
    already i have posted the question for this problem.
    but there i didn't explain properly.
    so, just bare with my explanation and give me solution.
    i am doing with Swings,
    I have,
    Master class ( having main())
    |
    |
    |
    V
    Sub Class-------> calling a thread class
    here the child class will throw a msgbox after its completion of execution to the sub-class interface.
    the code in the sub-class should continue only after the complete execution of the child thread, i.e after it got the msgbox thrown by child thread.
    say, on the 100th line of sub-class file we are calling the child thread, then the 101st line should not get executed before the child thread has executed completely.
    in my case it is getting executed.
    how to handle the situation.
    thanx in advance.
    --subbu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Hi, thank you for your reply.
    I am NOT creating a JVM in my C/C++ application.
    The problem is when I call __declspec( thread ), the system crash.
    Your suggestion is if I call from java to C++, for example, send data to C++, I do NOT need handle the thread whatever the C++ use thread and Socket.
    You are right. The C++ code works well in VC++ environment. And the JNI code works well to call simple C++ code (testing).
    I handle exception in Java side. That means I use try .. catch.. block to handle native method. But you mean I need check error and exception in C++ side ?
    For example
    jint err = env->MonitorEnter(obj);
    if (err)
         //todo
    else
    // todo
    I will handle it in the real code.
    I appreciate your suggestion.
    Have a good day
    anne

  • Home-made monitors for thread synchronization

    I have an assignment that request to implement a multiple-readers/one-writer algorithm on a shared ressource. I know Java already provide such methods as wait() and notify() but I have to write my own.
    So far, i have figured the startReading(), startWriting(), stopReading() and stopWriting() methods, but i don't understand how to write my own wait() and notify() methods. It was told that we could use a queue for the readers and another one for the writers. Also, i cannot use Threads anywhere.
    I find it very hard to figure it out. Anybody has an idea or some links where i could find the information?

    The purpose of the assignment is to understand how such mecanisms are working on a OS. We do this with a simulation. Maybe i didn't explain very well what i'm trying to do. Here is the code i've come with, it is working fine, but because i don't understand really well these mecanisms i am not sure it is good.
    class Dispatcher {
      Queue tpcb;                                 // All processes currently running
      MultipleReadersSingleWriterMonitor monitor; // Monitor for read/write lock
      Queue signaled;                             // Processes that were allowed to access the critical section
      public Dispatcher() {
        this.tpcb = new Queue();
        this.monitor = new MultipleReadersSingleWriterMonitor() {
          public void signal(final Processus p) {
            signaled.enqueue(p);
        this.signaled = new Queue();
      public void execute() { // When we arrive here, the tpcb has been filled
        for (Iterator i=tpcb.iterator(); i.hasNext(); ) { // Call the appropriate monitor for each processus
          Processus p = (Processus)i.next();
          if (p.mode == p.MODE_READ) {
            monitor.startReading(p);
          else {
            monitor.startWriting(p);
       // Pseudo-execute all the processus
       while (!tpcb.empty()) {
         if (!signaled.empty()) executeProcessus(signaled.dequeue());
      public void executeProcessus(Processus p) {
        // Code that simulate a processus running in the critical section
        // We are done, call the appropriate unlocking monitor
        if (p.mode == p.MODE_READ) {
          monitor.stopReading();
        else {
          monitor.stopWriting();
    }Anyway, unless i come with a suddent idea this is the final version. Thanx for answering.

  • Is singleton thread safe?

    hello all,
    please help me by answering these questions?
    singleton patterns calls for creation of a single class that can be shared between classes. since one class has been created
    Can singletons be used in a multithreaded environment? is singleton thread safe?
    Are threading problems a consequence of the pattern or programming language?
    thank you very much,
    Hiru

    Hi,
    Before explaining whether a singleton is thread safe
    e i want to explaing what is thread safe here
    When multiple threads execute a single instance of a
    program and therefore share memory, multiple threads
    could possibly be attempting to read and write to the
    same place in memory.If we have a multithreaded
    program, we will have multiple threads processing the
    same instance.What happens when Thread-A examines
    instance variable x? Notice how Thread-B has just
    incremented instance variable x. The problem here is
    Thread-A has written to the instance variable x and
    is not expecting that value to change unless Thread-A
    explicitly does so. Unfortunately Thread-B is
    thinking the same thing regarding itself; the only
    problem is they share the same variable.
    First method to make a program threadsafe-: Avoidance
    To ensure we have our own unique variable instance
    for each thread, we simply move the declaration of
    the variable from within the class to within the
    method using it. We have now changed our variable
    from an instance variable to a local variable. The
    difference is that, for each call to the method, a
    new variable is created; therefore, each thread has
    its own variable. Before, when the variable was an
    instance variable, the variable was shared for all
    threads processing that class instance. The following
    thread-safe code has a subtle, yet important,
    difference.
    second defense:Partial synchronization
    Thread synchronization is an important technique to
    know, but not one you want to throw at a solution
    unless required. Anytime you synchronize blocks of
    code, you introduce bottlenecks into your system.
    When you synchronize a code block, you tell the JVM
    that only one thread may be within this synchronized
    block of code at a given moment. If we run a
    multithreaded application and a thread runs into a
    synchronized code block being executed by another
    thread, the second thread must wait until the first
    thread exits that block.
    It is important to accurately identify which code
    block truly needs to be synchronized and to
    synchronize as little as possible. In our example, we
    assume that making our instance variable a local
    variable is not an option.
    Third Defence:--Whole synchronization
    Here u should implement an interface which make the
    whole class a thread safe on or synchronized
    Thre views are made by Phillip Bridgham, M.S., is a
    technologist for Comtech Integrated Systems.I'm
    inspired by this and posting the same hereWas there a point in all of that? The posted Singleton is thread-safe. Furthermore, some of that was misleading. A local variable is only duplicated if the method is synchronized, a premise I did not see established. Also, it is misleading to say that only one Thread can be in a synchronized block of code at any time because the same block may be using different monitors at runtime, in which case two threads could be in the same block of code at the same time.
    private Object lock;
    public void doSomething() {
        lock = new Object();
        synchronized(lock) {
            // Do something.
    }It is not guaranteed that only one Thread can enter that synchronized block because every Thread that calls doSomething() will end up synchronizing on another monitor.
    This is a trivial example and obviously something no competent developer would do, but it illustrates that the statement assumes premises that I have not seen established. It would be more accurate to say that only one Thread can enter a synchronized block so long as it uses the same monitor.
    It's also not noted in the discussion of local variables vs instance variables that what he says only applies to primitives. When it comes to actual Objects, just because the variable holding the reference is unique to each Thread does not make use of it thread-safe if it points to an Object to which references are held elsewhere.

  • Threads thrashing on synchronized queue

    Hi,
    I have been performing some tests on threads the past few days. I have a serious bottleneck in my application related specifically to thread synchronization.
    To test out the problematic thread issue, i created two Worker threads. So there are a total of 3 threads running including the Main thread (excluding GC etc).
    My test application extracts a Blob from a database and stores these in a simple synchronized queue. To test things, I pre cache 1000 Blobs (adding them into the Inbox queue) before runing my Worker threads.
    Once cached, I start the two Worker threads and let them consume and process the messages (Blobs).
    Worker Thread A collects a new message from the Inbox queue, processes it, and places it into and Outbox queue.
    Thread A continually retrieves messages from the Inbox using a synchronized remove() method.
    Thread B waits to receive messages into the Outbox queue. When a new message is received, it processes the message and subsequently retrieves another message in the queue.
    Both queues work on a FIFO policy.
    This test application models a simplified world of the real application which takes messages sent over TCP/IP, places them in an Inbox queue, and operations are performed on the message before being placed into an Outbox queue ready to be sent to another client.
    The problem is that there is serious overhead even with just these two threads. When the time taken to process a message is in general < 1ms, incurring 50+ms of overhead is exhorbitant.
    Below I have listed some example timings.
    I haven't changed the Thread priorities in this test run (they are set to NORM_PRIORITY). Even when setting Thread B to MAX_PRIORITY to consume blobs faster, the performance is still poor - I can see latencies between 1ms and 30ms.
    I'm running on a Win XP machine within Eclipse for the testing - even this shouldn't explain the overhead if the time to process the message is still fast. Does anyone have any suggestions on how to overcome this problem? Thread Pools and Executors don't seem necessary if there is issues when running only 2 threads. I've included the stripped down code (less any timing reports) below the output.
    Thanks,
    Mark
    Total Time = Time Thread B finished processing - Time Thread A collected the message
    Queue Count = You can see that the queue progressively banks up. Yet even with 0 or 1 messages in the queue, the overhead seems excessive
    Item ID, Total Time, Time to collect from Inbox (get), Process A, Time to collect from Outbox (get), Process B, Queue Count
    1,47.8712,0.0039,0.2863,0.0053,0.3554,1
    2,4.5017,0.0053,1.8497,0.0056,0.7414,0
    3,4.6693,0.0045,3.1887,0.1715,1.3370,1
    4,11.5911,0.0045,1.6505,0.0047,9.6889,1
    5,10.6402,0.0045,7.3199,0.0059,0.2858,0
    6,11.8498,0.0053,11.1467,2.8805,0.6358,1
    7,2.5716,0.0050,1.8611,0.0050,0.5001,0
    8,2.5654,0.0045,1.9852,0.0075,0.5017,0
    9,3.7952,0.0050,3.0685,1.7203,0.6406,0
    10,8.1049,0.0045,4.7456,6.5005,0.5355,2
    11,11.5110,0.0045,1.3591,0.0140,6.8553,3
    12,11.1632,0.0047,2.1078,0.0064,0.5962,2
    13,9.7638,0.0039,1.0621,0.0045,0.4216,1
    14,9.6554,0.0050,5.2445,0.0045,0.6780,0
    15,17.3190,0.0045,5.4418,3.8217,3.7982,7
    16,16.1839,0.0045,1.1300,0.0067,3.7661,13
    183,264.3495,0.0036,0.2646,0.0047,0.1523,177
    184,264.6873,0.0039,0.3162,0.0045,0.4665,176
    185,264.6387,0.0039,0.2640,0.0047,0.1486,175
    186,265.2667,0.0045,0.3445,0.0061,0.2207,174
    187,265.3038,0.0039,0.3665,0.0045,0.2579,173
    188,265.2239,0.0047,4.5092,0.0045,0.1687,172
    189,261.1888,0.0042,0.3970,0.0045,0.3400,171
    190,261.3304,0.0042,0.3780,0.0045,0.4031,170
    191,261.2142,0.0042,0.2671,0.0045,0.1467,169
    192,261.4762,0.0045,0.3224,0.0045,0.3777,168
    193,261.6176,0.0039,0.3087,0.0047,0.3271,167
    194,261.8464,0.0039,0.3084,0.0045,0.4026,166
    195,261.9841,0.0042,0.3707,0.0045,0.2296,165
    196,261.9858,0.0042,0.3774,0.0047,0.2514,164
    197,352.5018,0.0039,0.3595,0.0061,0.3724,320
    198,353.0776,0.0042,0.3224,0.0047,0.3724,324
    199,353.0513,0.0045,7.2205,0.0047,0.1640,323
    200,346.6273,0.0045,0.3447,0.0047,0.6152,322
    public class Collector implements Runnable{//extends Thread {
       MessageQueue inbox;
       MessageQueue outbox;
       public Collector(MessageQueue inbox, MessageQueue outbox) {
          this.inbox = inbox;
          this.outbox = outbox;
       public void collect() {
          MessageContainer mc;
          MessageInterface tx_msg;
          // start timing now
          mc = inbox.get(); // waits until a msg arrives
          // end timing how long it took to collect the msg
          if (outbox == null) {
             tx_msg = new TranslatedMessage(mc.the_message);
             mc.the_message.close();
             tx_msg.close();
             // stop timing here (Process B timing stopped)
             // output the timing report here
             mc = null;
          } else {
             // translate to XML - start timing Process arrives
             tx_msg = new XMLMessage(mc.the_message);
             mc.the_message.close();
             mc.the_message = tx_msg;
             // end time to process A
             outbox.put(mc);
             mc = null;
       public void run() {
          try {
             while (isRunning()) {
                collect();
          } catch (Exception e) {
             Debugger.println(e);
    public class MessageQueue {
       private LinkedList<MessageContainer> queue;
       private int put = 0;
       private int recd = 0;
       private int tally = 0;
       private Object tallyLock = new Object();
       /** Creates a new instance of MessageQueue */
       public MessageQueue() {
          queue = new LinkedList<MessageContainer>();
        * Places the given message in the queue to await consumption
        * @param message The message to store in the queue
        * @param id The message identifier
        * @param bytes The size in bytes
       public void put(MessageInterface message, String id, int bytes) {
          put( new MessageContainer(message, id, bytes) );
       public void put(MessageContainer message) {
          if (message != null) {
             synchronized(queue) {
                queue.add( message );
                put++;
                synchronized(tallyLock) {
                   tally++;
                   tallyLock.notify();
                queue.notify();
        * Conditional to test whether the queue has any messages
        * @return True if the queue is empty, false otherwise
       public synchronized boolean isEmpty() {
          return queue.isEmpty();
        * Get the message at the top of the queue's stack.
        * If there are no messages in the queue,
        * then sit and wait until one becomes available.
        * Handles things using a first in, first out policy.
        * @return The interface message at the front of the queue
       public MessageContainer get() {
          MessageContainer message = null;
          synchronized(queue) {
             while( queue.isEmpty() ) {
                try {
                   queue.wait();
                } catch( InterruptedException ie ) {
             message = ( MessageContainer )queue.removeFirst();
             recd++;
             queue.notify();
          synchronized(tallyLock) {
             tally--;
             tallyLock.notify();
          return message;
       public int getTally() {
          synchronized(tallyLock) {
             return tally;
       public void waitTillEmpty() {
          synchronized(queue) {
             while( !queue.isEmpty() ) {
                try {
                   queue.wait();
                } catch( InterruptedException ie ) {
    }

    Hi TBemis,
    I implemented Collections.synchronizedList() but without luck. I think the problem is due to thread scheduling? One thread seems to be starved of CPU (namely the second thread which consumes the message and outputs the timing report) while the other - the producer - seems to tie things up and hogging CPU to put more messages in it's Outbox. CPU usage is not extreme when I run the application (1-5%) but what the test does require, Thread #1 seems to hog CPU cycles.
    I should have mentioned in the initial post that BLOBs are never larger than 36Kb so not too large. So I wouldn't expect the GC to be the culprit? The times (a couple of hundred milliseconds) seems very exorbitant for GC.
    Also should have mentioned, the test I performed creates two threads (classic producer-consumer scenario). One is initialised with an Inbox (housing the messages from the database) and an Outbox to pass translated messages into. The other simply has an inbox (a handle to the the producer's outbox).
    I conducted some more tests yesterday. I introduced a sleep of 1 millisecond and you can see that the thrashing is reduced dramatically. Now the time taken overall is regularly under 1 ms long. I introduced the sleep after the call to add a new message into the Outbox of Thread A:
    try { Thread.currentThread().sleep(1); } catch (InterruptedException ie) {}
    New times:
    Total Time = Time Thread B finished processing - Time Thread A collected the blob
    Item ID, Total Time, Time to collect from Inbox (get), Process A, Time to collect from Outbox (get), Process B, Queue Count
    1,0.4014,0.0064,0.2053,0.9579,0.1592,0
    2,0.9255,0.0335,0.3989,1.9123,0.4431,0
    3,0.8171,0.0092,0.3914,1.3169,0.3688,0
    4,0.5135,0.0101,0.3291,1.4175,0.1442,0
    5,0.5395,0.0081,0.3185,1.7139,0.1841,0
    6,0.7680,0.0084,0.3875,1.7583,0.3243,0
    7,0.6428,0.0204,0.3836,1.5611,0.2104,0
    8,1.3186,0.0416,0.4590,1.7307,0.7685,0
    9,0.5118,0.0584,0.2897,0.9146,0.1349,0
    10,0.7859,0.0092,0.3903,1.7851,0.3378,0
    11,0.4693,0.0087,0.3031,1.4225,0.1293,0
    12,0.9124,0.0081,0.3805,1.8863,0.4095,0
    13,0.4911,0.0084,0.3193,1.3071,0.1341,0
    14,2.0899,0.0098,0.6727,2.0885,0.3531,1
    15,0.4425,0.0056,0.1673,0.0036,0.2056,0
    Is there any way to overcome this poor thread scheduling without resorting to changing thread priorities or introducing artificial delays?

  • Problem with threads communication

    Hi All
    I have a multithreaded application in which I have 3 threads running including main thread. One of the thread (Thread1) spawned by main thread is performing the business logic required. The other one (Thread 2) is just to send the periodic signals to an admin application that it is alive. Now I need to pass some data obtained from business logic (Thread1) to the second thread (Thread2). How can i do that.? I need the data from Thread1 to Thread2 every time, the thread2 send the alive request to admin application.
    Thanks & Regards
    Inder Jeet Singh

    See Producer/Consumer example at for 2 threads exchanging data:
    http://java.sun.com/docs/books/tutorial/essential/threads/synchronization.html
    In your case it seems reasonable to store data somewhere until T2 will use it during sending
    alive request to admin application

  • Interrupting a Thread in a Remote Object?

    HI,
    I am trying to get some thread synchronization to happen between a client and a remote RMI object. Essentially what I am trying to accomplish, is that if I interrupt a call on a blocking method in the remote object, I want the thread to throw the InterruptException. For example, the following code represents what I am trying to accomplish:
    package bca.test.rmi;
    import java.rmi.Naming;
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    public class InterruptThreadApp {
    RemoteBlockingObjectInt remote = null;
    public static void main(String[] args) throws Exception {
    //Create the remote object
    RemoteBlockingObject obj = new RemoteBlockingObject();
    //bind it to the registry
    Naming.rebind("rmi://localhost/blocking", obj);
    //start the client, or the thread which will access the blocking call remotely
    InterruptThreadApp app = new InterruptThreadApp();
    Thread blocking = null;
    //wait for the thread to start
    synchronized ( app ) {
    blocking = app.startClient();
    app.wait();
    Thread.sleep(2000);
    //now interrupt the thread (note: the remote object should be blocking in
    //the blockingMethod().. this should produce an InterruptException?
    blocking.interrupt();
    public Thread startClient() {
    Thread t = new Thread("Client") {
    public void run() {
    try {
    //get a handle to the stub
    remote = (RemoteBlockingObjectInt) Naming.lookup("rmi://localhost/blocking");
    //now make a call to the blocking method, but first wake up the client
    synchronized ( InterruptThreadApp.this ) {
    InterruptThreadApp.this.notify();
    //now make the blocking call
    remote.blockingMethod();
    catch (InterruptedException e) {
    System.out.println("WooHoo! This is what we want! But it never gets thrown :(");
    catch (Exception e) {
    e.printStackTrace();
    t.start();
    return t;
    package bca.test.rmi;
    import java.rmi.server.UnicastRemoteObject;
    import java.rmi.RemoteException;
    import java.rmi.Remote;
    public class RemoteBlockingObject extends UnicastRemoteObject implements RemoteBlockingObjectInt {
    Object obj = new Object();
    public RemoteBlockingObject() throws RemoteException {
    super();
    public void blockingMethod() throws RemoteException, InterruptedException {
    synchronized (obj) {
    System.out.println("About to block.. so we can be interrupted later");
    obj.wait();
    interface RemoteBlockingObjectInt extends Remote {
    public void blockingMethod() throws RemoteException, InterruptedException;
    When I make a call to "remote.blockingMethod()", it blocks in the remote object (buy just "wait" ing). I want to interrupt this thread, by issuing an Thread.interrupt(). When I do so (I call "blocking.interrupt()"), nothing happens... no exception is thrown.. it just silently fails.
    Ok, so I suppose that we can not interrupt a remote thread.. that is fine. But what if I want to interrupt the RMI thread making the remote call? I don't want it to block forever. How can I "cancel" the remote call?
    Ideally, I would like the remote.blockingMethod() call to throw an InterruptException when I issue an "interrupt()" on the blocking thread. Any suggestions on how I might accomplish this?
    Thanks,
    Bryan

    While you can interrupt the RMI call, you cannot stop the active processing. That is, you cannot force a thread to stop (see the Java API documentation on Thread.stop().)
    Since the Client RMI call is a waiting thread, you need another Client thread to do a secondary RMI call. The trick is to have the new RMI endpoint connection thread on the RMI Server interrupt the original RMI endpoint connection thread.
    The only way you can interrupt an RMI call is to have the endpoint connection thread that runs on the RMI Server be aware that the user may wish to interrupt it.
    The best means of interruption is for the endpoint connection thread to use "worker threads". The endpoint connection thread waits for the workers to finish and is interruptible by both the workers and other endpoint connection threads.
    Another means of interruption is for the endpoint connection thread to segment the task into units of work and check for an interruption between those units of work.
    There are two ways I've done RMI call interruption.
    One is for the Client to pass a unique id (UID -- that uniquely identifies the request) to the Server with the original call. When the Client wishes to interrupt the original call, using the separate thread, it does a new RMI call to the Server passing the UID.
    The new endpoint connection thread, using the UID, interrupts the original endpoint connection thread.
    The major problem with this is the unique id. It absolutely, positively must be unique. Otherwise you run the risk of Client_A purging Client_B's request.
    The second method requires callback. If your Client is behind a firewall then RMI callback is near impossible. In such a case you must come up with a way for the Server to call the Client that is secure (the firewall problem.)
    The Client must export a remote object and pass that remote object to the Server with the original call.
    The endpoint connection thread recognizes the remote object and does a call back to the Client passing information that uniquely identifies itself (UID). Since the Server generates the UID, it can guarantee uniqueness.
    The Client callback implementation runs as a separate thread since the Client is in fact an RMI Server itself (when it did the export.) The Client must save the UID. The Client must start a new thread for the interrupt procedure or inform a waiting thread that the Server called back.
    Just like method one, above, when the Client wishes to interrupt the original call, using the separate thread, it does a new RMI call to the Server passing the UID.
    The new endpoint connection thread, using the UID, interrupts the original endpoint connection thread. Simple.
    For an academic example using call back go over to Jini.org. They have an example called "Cancellation" at:
    http://starterkit-examples.jini.org/
    For a professional, open source implementation of both these methods go over to CoopSoft.com. The Tymeac (Java) projects support canceling both waiting and autonomous requests at:
    http://www.coopsoft.com/JavaProduct.html

  • Code synchronization across the cluster

    Do the App Servers take care of synchronizing webapp java code across multiple nodes of a cluster.
    or does synchronizing work only on a single JVM
    Thanks,
    Sunil.

    When you talk of synchronization do you mean more than one thread accessing mutable object state or synchronizing serialized session data per node such as data stored in the HTTP session?
    For the thread synchronization which is what I think you mean, a thread on machine A running on JVM 1 cannot access an object running on machine B under JVM 2 so there is no need to worry about synchronization.
    In the second instance, there is nothing concrete in the Java EE spec therefore it is up to the vendor, but typically this is handled.

  • Thread Contention

    I've written a producer/consumer type of application. the producer receives data input (speed and time) over a serial connection and places it in a queue of sorts, set up much like the examples at Sun. The consumer picks up the values, calculates a speed and moves an animation object across a display.
    I've put both the consumer and producer programs in their own threads. the driver program starts the producer program in its thread and calls an openConnection method to open a serial connection. I then call a startCollecting method that begins reading serial input. The input is dumped in the queue, which has a capacity of 5 values. If the producer fills all five values, it goes into a wait state. the consumer is supposed to pick up the values, freeing the producer to place more values in the queue. My problem is once the producer goes into its wait state, everything freezes, including the driver program interface, and the visual display the consumer is running in.
    If I do not call the openConnection and startCollecting separately, but rather just start the producer thread and let it open a connection and start collecting automatically all runs well. It seems the problem exist whenever I attempt to access methods inside the threaded program.
    Any help would be greatly appreciated. Have not found any really examples of how to resolve this approach.

    I've put both the consumer and producer programs in
    their own threads.good.
    the driver program starts the
    producer program in its thread and calls an
    openConnection method to open a serial connection. I
    then call a startCollecting method that begins reading
    serial input. The input is dumped in the queue, which
    has a capacity of 5 values. If the producer fills all
    five values, it goes into a wait state. the consumer
    is supposed to pick up the values, freeing the
    producer to place more values in the queue. My problem
    is once the producer goes into its wait state,
    everything freezes, including the driver program
    interface, and the visual display the consumer is
    running in. this sounds like you possibly missed something in the area of thread synchronization. did you invoke notifyAll() after you put somthing in the queue?
    the typical queue implementation looks like this:
    package farmerworker;
    import java.util.*;
    * A thread safe queue used to synchronize farmers and workers. Farmers put
    * objects into the queue and workers retrieve them. Workers may arbitrarily
    * invoke {@link #dequeue()}. Their thread blocks until an instance can be
    * retrieved from the queue or the thread is interrupted. <p>
    * technically {@link #enqueue( Object )} and {@link #dequeue()} are
    * synchronized using {@link #wait()} and {@ #notify()}.
    * @author    klemme
    * @created   24. September 2001
    * @version   $Revision$
    public class Queue {
         * Checks whether there are objects in the queue.
         * @return   'true' if there are instances in the queue. WARNING: in a
         *      multithreaded environment it is only reasonable to invoke this
         *      method when holding a lock on this instance, i.e. in a <code>synchronized</code>
         *      block.
        public boolean isEmpty() {
            synchronized ( lock ) {
                return queue.isEmpty();
         * Return the number of objects currently in the queue.
         * @return   a value >= 0
        public int size() {
            synchronized ( lock ) {
                return queue.size();
         * Put an object into the queue.
         * @param obj  the instance to enque
        public void enqueue( Object obj ) {
            synchronized ( lock ) {
                queue.add( obj );
                lock.notify();
         * Retrieve something from the queue. This method blocks until either an
         * Object can be retrieved from the queue or this thread is interrupted.
         * @return                          the next Object in the queue
         * @exception InterruptedException  in case of premature termination of this
         *      thread.
        public Object dequeue()
            throws InterruptedException {
            synchronized ( lock ) {
                while ( isEmpty() ) {
                    lock.wait();
                return queue.remove( 0 );
        private List queue = new LinkedList();
         * The lock on which this instance synchronizes.
        protected final Object lock = queue;
    [/code}]instead of synchronizing on "lock" you can just synchronize methods.  then you have to invoke notifyAll() and wait() on "this".  you can also change the conditions when the queue accepts new input.  this Queue is unbounded, but you can implement a size limit via a condition testing for the size in enqueue(). (typically this is easier done then working with a ring buffer in a fixed sized array, since then you need two indexes etc. and the overhead of a LinkedList is not too big. - btw: LinkedList is faster than ArrayList if you don't need indexed access like in this case.)
    regards
    robert

Maybe you are looking for