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.

Similar Messages

  • [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

  • 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

  • Some question on thread

    i think threads are unpredictable.say, the following code. some questions on the code.
    public class Rpcraven{
         public static void main(String argv[]){
         Pmcraven pm1 = new Pmcraven("One");
         pm1.run(); // line1
         Pmcraven pm2 = new Pmcraven("Two");
         pm2.run();  // line 2
    class Pmcraven extends Thread{
    private String sTname="";
    Pmcraven(String s){
         sTname = s;
    public void run(){
         for(int i =0; i < 2 ; i++){
              try{
               sleep(1000);
              }catch(InterruptedException e){}
              yield();
              System.out.println(sTname);
    }question 1 > note line 1 and line 2 . does this two threds are staarted at the same time ? or line 1 first and line 2 second as in the code ? this is very much important to me.
    question 2 > ok, whoever goes first , now lets come to the try-catch block . there is sleep() who will sleep first ? so i need to know which thread is going to sleep first ? bcoz then i can say who will get the yield() method.
    i find difficult to predict the output of this thred.
    Output of One One Two Two.
    one more thing, threads are always called by start() method ( run() is called implicitly) . here start() is not usued . still the code is working . how ?

    question 1 > note line 1 and line 2 . does this two
    threds are staarted at the same time ? or line 1 first
    and line 2 second as in the code ? this is very much
    important to me.If it's important, you are doing something wrong...
    First, you shouldn't call the threads' run() method, that doesn't "start" the thread, it just calls run(). Use start() instead.
    The threads are sort of started in order, but probably not in the way you think.
    Think of it like this: there is a list of threads in the JVM. start() puts the thread in the list. After that, the CPU of your computer can run any thread in the list, for as long as it feels like. The CPU might run thread 1 for a few instructions, then thread 2 for a while, or it might start with thread 2, ... If you have a multi-CPU machine, the threads are run at the same time. It's unpredictable, except when you do explicit synhcronization or waiting.
    question 2 > ok, whoever goes first , now lets come to
    the try-catch block . there is sleep() who will sleep
    first ? so i need to know which thread is going to
    sleep first ?This is unpredictable. You can't know it. It will vary from run to run.
    If you need two threads to do something in a predictable order, you'll need to do synchronization and waiting.
    one more thing, threads are always called by start()
    method ( run() is called implicitly) . here start()
    is not usued . still the code is working . how ?You are not starting the threads, you are calling their run() methods sequentially.

  • Question about Threads

    Hi,
    imagine that I have a class as below:
    public class MyVector
    private IntegerVector vect;
    public Synchronized void write(){
    vect.f();
    public Synchronized void read(){
    vect.g();
    Where f and g are non Synchronized and non-static public methods of IntegerVector .
    Imagine that two threads as below:
    thread one :
    class ThreadOne extends Thread
    public ThreadOne(MyVector v)
    this.v=v;
    public void run()
    v.write();
    class ThreadTwo extends Thread
    public ThreadTwo(MyVector v)
    this.v=v;
    public void run()
    v.read();
    My question is that if there will be any conflict between thread1 and thread2 for having the lock on
    object MyVector v ?the methods read and write are Synchronized but they call non-Synchronized methods f() and g()
    of field "IntegerVector vect" of "MyVector v "!
    Thanks,
    Behnaz

    bandarurm wrote:
    jverd wrote:
    bandarurm wrote:
    @OP - Also, remember that there are only two types of locks (aka monitors), which are Object level lock and Class level lock. No. All locks are identical.Could you explain this further? As I thought there is a class level lock (java.lang.Class) for a class with static synchronized methods. And, there is an object level lock, which is a built-in lock that every object has in java, by default.Whenever you synchronize a block of code or a method, you're just obtaining some object's lock. Synchronized methods are just shorthand for obtaining particular objects' locks.
    Synchronization is always the same. Declaring a method synchronized is just shorthand for what you could do by explicitly syncing a block of code on a particular object.
    class Foo {
      synchronized void bar() {
        // body
      // is the same as
      void bar() {
        synchronized (this) {
          // body
      // and
      static synchronized qux() {
        // body
      // is the same as
      static qux() {
        synchronized (Foo.class) {
          // body
    }In all cases, you're just syncing on an object, and which object doesn't matter, except to other methods or blocks that sync on the same object. Everything else is identical.
    The fact that synchronized static methods obtain one particular lock and non-static ones obtain a different one is not indicative of different kinds of locks. It's always just some object's lock, and no lock behaves differently from any other.
    Edited by: jverd on Apr 20, 2009 10:46 AM

  • Follow-up question to thread 'Sort by "total" in Answers'

    Seems I was a bit too quick in closing.
    Sorry for opening two threads on this, but I need to get this solved as I'm on a tight deadline here...
    The answer that pretty much solved my issue on sorting columns on sub-totals in Answers was:
    if you want to sort on sub-totals, follow this:
    i'm assuming that for that profitability column sub-total is sum of individual values for that segment..
    create other column in criteria tab:
    change it's fx to: sum(Profitability by Year, Sector)
    then, keep first sort order asc/desc on this column
    hide this column
    apply 2nd sort order asc/desc on normal profitability column..
    hope it resolve your issue.... I just have one more quick question:
    I can now sort according to sub-total, but how can I hide this new column from my table view? Clicking on the red 'x' button totally removes it as a filter.. The "hide" checkbox in the properties of the column simply grays the column out and shows it without any numbers.
    Thanks in advance
    - Magnus

    go to column properties (first option) > Column Format tab
    you find hide check box.. select and save.
    grays out the values in the column, which is correct and the same what we want..
    But, you should look at that in compound layout, not in edit properties of table...
    in compound layout, appears like it's hidden
    or
    achieve everything in pivot then exlude that particular column
    Edited by: Kishore Guggilla on Nov 29, 2010 7:18 PM

  • A question in threading

    Hi everybody,
    my problem is as follow, I have two classes myClass and myGUI
    myClass code is
    public class MyClass
         public void start()
              while (true)
                   // do some stuff
         public void stop()
              System.out.println("Hello from stop method!");
    }myGUI code is
    public class MyGUI extends javax.swing.JFrame
    MyClass cl = new MyClass();
    public static void main(String[] args)
                        MyGUI inst = new MyGUI();
                        inst.setLocationRelativeTo(null);
                        inst.setVisible(true);
    public MyGUI()
              super();
              initGUI();
    private void initGUI()
    // some GUI code
    myStartBtn.addActionListener(new ActionListener()
                             public void actionPerformed(ActionEvent evt)
                                  cl.start();
    myStopBtn.addActionListener(new ActionListener()
                             public void actionPerformed(ActionEvent evt)
                                  cl.stop();
    }as you can see, the start() method puts the program in an infinite loop, which makes me unable to call the stop() method using myStopBtn... So, I think this can be done using threads but actually I don't know how exactly am gonna do this
    So, any help will be appreciated.
    Thanks

    This has nothing to do with JSF.
    If you have a Concurrency specific question, post it in the Concurrency forum.
    http://forum.java.sun.com/forum.jspa?forumID=534
    If you have a Swing specific question, post it in the Swing forum.
    http://forum.java.sun.com/forum.jspa?forumID=57

  • 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.

  • A question about thread safety and the Acrobat SDK

    Hi All,
    On page 12 of this FAQ: http://www.adobe.com/devnet/acrobat/pdfs/Acrobat_SDK_developer_faq.pdf
    It says that Use of any Acrobat product in a multithreaded way is technically impossible.
    I'm currently writing a command line application to perform some basic data gathering on a PDF file. The Application only makes use of a PDDoc object, and never calls on any other kind of object (i.e. AVDoc).
    The application itself is not multithreaded. All of the logic runs in a single thread.
    However, the application will be called (via the command line) from another application that /is/ multithreaded. I think that this might be fine, but I wasn't sure. In this case, would this count as a single thread, but spread across multiple processes? And if that is the case, would that be OK with the SDK?
    Or would having multiple invocations/calls into the Acrobat DLLs cause the same issue as a multi-threaded application?
    Unfortunately, I haven't done a lot of work with threads before. This might be a very silly question.

    The application would be called from a perl script that is used to automate several tasks. The app is a console application, written in C# w/ the Acrobat COM components, and Visual Studio 2005.
    The console application uses the Acrobat SDK to instantiate a PDDoc object, open a PDF, and get information about the document. It then returns results back to the console.
    So, the perl script just calls: "C:\pdfinfo.exe -f=myPdf.pdf" and pipes the result to a log file.
    In this case, it never creates a new instance of the Acrobat application, but it does use the SDK.
    The reason that I was concerned was that the perl script is multi-threaded. I wasn't sure if acrobat was just sensitive to multiple threads inside a single process, or if it was unable to handle multiple processes as well.
    PDL's answer suggests that I should be fine as long as a new process is started each time. This is good to hear.

  • Very Basic Question on Threads and Object Manipulation between classes

    I have a feeling this is on the virge of being a stupid question but hey, its the right forum.
    Lets assume I have a class that extends Jframe : Jframe1
    In that frame there is only one Jlabel : Jlabel1
    I want to create a thread that will affect Jlabel1
    The thread will run an endless loop that will.. for example change the color of the label to a random color and then the thread will sleep for a given time. There is no use in this program. Its only meant to help me understand
    I have looked up info and examples on threads. Unfortunately none were useful. Most examples try to illustrate the use of threads with the example of an applet digital clock. But it does not help with my problem, not to mention I dont want to delve into applets at this time.
    I know I have to make a class that extends thread. Does it have to be an inner class?
    How do I get to affect the frame's Jlabel1 from it? It says it doesn't know anything about it.

    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class Jframe1 extends JFrame implements Runnable{
      Container con;
      JLabel Jlabel1;
      Random rand;
      Color c;
      public Jframe1(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        con = getContentPane();
        rand = new Random();
        Jlabel1 = new JLabel("bspus", JLabel.CENTER);
        Jlabel1.setOpaque(true);
        con.add(Jlabel1, BorderLayout.NORTH);
        setSize(300, 300);
        setVisible(true);
      public void run(){
        while (true){
          try{
            Thread.sleep(1000);
          catch (InterruptedException e){
            break;
          int n = rand.nextInt(16777216);
          c = new Color(n);
          SwingUtilities.invokeLater(new Runnable(){
            public void run(){
              Jlabel1.setBackground(c);
      public static void main(String[] args){
        Jframe1 jf = new Jframe1();
        new Thread(jf).start(); // you don't need to create a new thread
      }                         // because this Main thread is just
                                // another thread.
                                // here, only for demonstration purpose,
    }                           // we make a new separate thread.

  • Another question about threads

    Hi guys,
    I'm looking for a method to pause a thread for some time. I tried sleep(), but sleep() executes the run method after "sleeping".
    I just want a method to stop execution and resume at the same line of code. Is there a way I can do this?

    You have to call the wait on the object you are waiting on not the wait for the current thread.
    To get the monitor you have to synchronize on the queue
    eg
    run()
    synchronized(myQueue)
    if(myQueue.isEmpty())
    myQueue.wait();
    ....// process queue
    }// run()
    in the myQueue src code you need a method such as
    public void synchronized add(Object o)
    notifyAll(); // wakes up threads
    }

  • Question on Thread concurrency

    If two threads execute the below method increment() concurrently, how many different final values of X are there? You may assume that initially X has value 0.
    void increment()
    int temp = x;
    temp = temp + 1;
    x = temp;
    }

    That's enough of these questions. It's not a homework service. Locking this thread.

  • Question on Thread

    Hi All
    I got a doubt while implementing threads, so thought of getting it cleared before i do some progress. I have a method from where the new thread is getting called and in the next line i have return statement.
    Method(){
    Calling thread ();
    return statement;
    What happens here? I mean Does the parent process completes before the child process?
    Thanks
    Simi

    user11138361 wrote:
    I exactly mean the same
    int foo() {
    Runnable r = new MyRunnable();
    Thread t = new Thread(r);
    t.start();
    return 1;
    My question was If the child process is running then how the parent process(Px) will complete ?There is no child process. You're creating a thread, not a process.
    That point aside, I don't understand your question. The current thread and the new thread are totally independent of each other. Why would you expect that one can't complete while the other is still running?
    Also note that the parent thread is NOT the same as that foo() method. The thread doesn't necessarily end when the foo() method does. It can, though, and I don't know why you'd think otherwise.
    EDIT: My guess is that what you're really confused about is, "How can method foo() end when one of its 'steps' (that is, the new thread) is still executing?" The answer is that all of its steps are done, even if the other thread is still running.
    foo()'s step of calling t.start() has finished. That doesn't mean the new thread has finished, however. The start() method says, "create a new, +independent+ thread of execution and set it running." As soon as it does that, start() is done, and now the new thread is running (or eligible to run) independently of the current thread.
    Imagine I have a list of chores: Take out trash; Wash dishes; Vacuum living room. That list is the foo() method. You are a new Thread object. After I wash the dishes, I tell you "Go to the store, and buy apples, milk, eggs, chicken, and bread." You leave to do your work, and as soon as I have told you what to do, I continue with my tasks. We do our work independently of each other, and I can finish the chores on my list without waiting for you to come back from the store.
    Edited by: jverd on Mar 21, 2011 11:27 AM

  • Another question about Thread! 'theJava' are prohibited!

    hi,guys!
    the code seems grown:)
    but it is still confused:~
    public class Test extends Thread{
         private boolean direct;
         Item item=null;
         public static void main(String argv[]){
              Item item=new Item(0);
              Test thread1=new Test(true,item);
              Test thread2=new Test(false,item);
              thread1.start();
              thread2.start();
         Test(boolean direct,Item item){
              this.direct=direct;
              this.item=item;
         public void run(){
              synchronized(item.part){
              /*synchronized(item){ here it works properly, for the item
              locked prevent any other thread's modification
              but why does 'item.part' take the same effect as above?
              what on earth does 'synchronized(x)' mean?
              does it lock the behaviors only on object x?
              could i lock member object of object x as above?
              for(int i=1;i<10;i++){
                   try{Thread.sleep(1000);}catch(InterruptedException ie){}
                   if(direct==true)
                        item.addValue();
                   else
                        item.reduceValue();
                   System.out.println((direct==true?"add value:":"reduce value:")+item.getValue());
    class Item{
         private int value;
         public Object part=new Object();
         Item(int i){
              value=i;
         public void addValue(){
              value++;
         public void reduceValue(){
              value--;
         public int getValue(){
              return value;
    thanks again.

    Here is the code in code tags, changed a little so I have Item as a static inner class (this has no effect on the running of the code either)..
    hi,guys!
    the code seems grown:)
    but it is still confused:~
    public class Test extends Thread {
        private boolean direct;
        Item item=null;
        public static void main(String argv[]) {
            Item item=new Item(0);
            Test thread1=new Test(true,item);
            Test thread2=new Test(false,item);
            thread1.start();
            thread2.start();
        Test(boolean direct, Item item) {
            this.direct=direct;
            this.item=new Item(0);
        public void run() {
            synchronized(item.part) {
                //* synchronized(item){ here it works properly, for the item
                //* locked prevent any other thread's modification
                //* but why does 'item.part' take the same effect as above?
                //* what on earth does 'synchronized(x)' mean?
                //* does it lock the behaviors only on object x?
                //*   could i lock member object of object x as above?
                for(int i=1;i<10;i++) {
                    try{
                        Thread.sleep(1000);
                    } catch(InterruptedException ie) { }
                    if(direct==true)
                        item.addValue();
                    else
                        item.reduceValue();
                    System.out.println((direct==true?"add value:":"reduce value:")+item.getValue());
        static class Item {
            private int value;
            public Object part=new Object();
            Item(int i) {
                value=i;
            public void addValue() {
                value++;
            public void reduceValue(){
                value--;
            public int getValue(){
                return value;
    }thanks again.
    Ok, the synchronized keyword takes an object as its parameter. This object is used by the objects monitor to make sure that no more than 1 thread may access it at a time for the duration of the synchronized block. Ok so far?
    The synchronized(item.part) works exactly the same way as synchronized(item) because part is a member of the item class. The monitor is just locking different objects, part happens to belong to item hence the effect of the lock is apparently the same.
    Variation 1. If the value for direct is true, sychronize on item. If false synchronize on item.part.
    Here is the code for you...
            synchronized((direct == true ? item : item.part)) {Run that and see what happens.
    Variant 2
    If you create 2 Item objects, assign the first one as you did before but the second 1 to the second Test instance then you will see that both threads now run side by side.
    Here is the code for that as well. Make sure that the synchronized code is the same as the original.
            Item item=new Item(0);
            Item item1 = new Item(0);
            Test thread1=new Test(true,item);
            Test thread2=new Test(false,item1);Hope this helps

Maybe you are looking for

  • How to add jar files in project?

    Hi everyone, Im stuck at one problem. I have third party API which are in jar files. I want to add reference those jar files in my projects. How to add all jar files at once in my project? Also, jar files are in different folders, like rootFolder {no

  • Accessing fields of the af:Query Component

    Hi all, I need to get the value of a dynamic field that is added to the query component at runtime. In my application there is field named "Member Id" which adds a "select one component" in the advanced search mode. This "select one component" has a

  • Can't End Call with Bluetooth Headset

    Having just purchased a Blackberry 8330, I am disappointed with the inability to end a call with a Bluetooth hands free device (Jabra VBT185Z).  The hang-up problem occurs when the Blackberry is locked and a call is placed with the Bluetooth device.

  • How to execute system command from java program

    Hi all, I want to change directory path and then execute bash and other unix commands from a java program. When I execute them separately, it's working. Even in different try-catch block it's working but when I try to incorporate both of them in same

  • Handling multiple clients

    I am trying to create a server that accepts multiple connections. I know that this question is asked a lot, but I cannot figure out what is wrong with mine...aside, possibly, everything. This is my server code, I used a frame to display this informat