Creating a java thread in a jframe class?

hello is this possible to create a thread for a jframe class? so that everytime a connection is established, a new thread along with the gui is opened automaticly? if so, would i just need to insert extends Thread on my declaration of my class?
i already have this code at the top of my jframe class..
public class ChatDialog extends javax.swing.JFrame implements WindowListenerwhere and how would i implement the run() method in thsi class?
full code:
package icomm;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ChatDialog extends javax.swing.JFrame implements WindowListener {
    protected String messege;
    private Socket client_user = null;
    /** Creates new form ChatDialog */
    public ChatDialog()
        initComponents();
        addWindowListener( this );
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        convo_txt = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        txt_messege = new javax.swing.JTextArea();
        send_button = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        Option = new javax.swing.JMenu();
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane1.setViewportView(convo_txt);
        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 220, 270));
        jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        txt_messege.setLineWrap(true);
        jScrollPane2.setViewportView(txt_messege);
        getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 310, 220, 70));
        send_button.setText("Send");
        send_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                send_buttonActionPerformed(evt);
        getContentPane().add(send_button, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 390, -1, -1));
        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);
        Option.setText("Option");
        jMenuBar1.add(Option);
        setJMenuBar(jMenuBar1);
        pack();
    // </editor-fold>
    private void send_buttonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        //get txt from textbox   
        String text = txt_messege.getText();
    public void windowClosing(WindowEvent e)
        public void windowActivated(WindowEvent e) {}
     public void windowClosed(WindowEvent e) {}
     public void windowDeactivated(WindowEvent e) {}
     public void windowDeiconified(WindowEvent e) {}
     public void windowIconified(WindowEvent e) {}
      public void windowOpened(WindowEvent e)
     * @param args the command line arguments
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ChatDialog().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JMenu Option;
    private javax.swing.JTextArea convo_txt;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton send_button;
    private javax.swing.JTextArea txt_messege;
    // End of variables declaration
}

Instead of attempting to have the frame extend thread (or implement Runnable which is actually possible since you cannot have multiple inferitance). You might want to just create the frame and have that frame lauch an associated thread to take care of the processing required.

Similar Messages

  • How to use Java threads in ColdFusion

    Hello Everybody,
    I have a question in concerns to threads. We all know that in
    CF8 we have this fantastic tag called <cfthread> which give
    us the ability to create assyncronous code, however, I was
    concerned about earlier versions of ColdFusion, like CF7 and CF
    6.1.
    How can I create a Java thread and use it in my CF code?
    Please, any help is much appreciated. Thanks in advance.
    Alvaro Costa
    Systems Analyst
    [email protected]

    A bean is obtain by <jsp:useBean> tag nd once bean is obtained we can get its property by using getProperty tag.

  • Java.lang.OutOfMemoryError: unable to create new native thread

    Hi All,
    I have installed weblogic server 8 sp4 in production environment . I am facing problems with JVM issues .
    JVM is crashing very frequently with the following errro :
    ####<Jun 18, 2009 10:58:22 AM IST> <Info> <Common> <IMM90K-21> <SalesCom> <ExecuteThread: '24' for queue: 'weblogic.kernel.Default'> <<anonymous>> <> <BEA-000628> <Created "1" resources for pool "PIConnectionPool", out of which "1" are available and "0" are unavailable.>
    ####<Jun 18, 2009 11:00:09 AM IST> <Info> <EJB> <IMM90K-21> <SalesCom> <ExecuteThread: '23' for queue: 'weblogic.kernel.Default'> <<anonymous>> <> <BEA-010051> <EJB Exception occurred during invocation from home: payoutCheck.ejb.payoutCheck_s6v3so_HomeImpl@121a735 threw exception: java.lang.OutOfMemoryError: unable to create new native thread
    java.lang.OutOfMemoryError: unable to create new native thread
         at java.lang.Thread.start(Native Method)
         at payoutCheck.classes.MyThread2.MyThreadv(PayoutCheckBOImpl.java:249)
         at payoutCheck.classes.PayoutCheckBOImpl.genSP(PayoutCheckBOImpl.java:184)
         at payoutCheck.ejb.PayoutCheckSLSB.genSP(PayoutCheckSLSB.java:191)
         at payoutCheck.ejb.payoutCheck_s6v3so_EOImpl.genSP(payoutCheck_s6v3so_EOImpl.java:315)
         at payoutCheck.ejb.payoutCheck_s6v3so_EOImpl_CBV.genSP(Unknown Source)
         at payoutCheck.deligate.PayoutCheckBD.genSP(PayoutCheckBD.java:226)
         at ui.action.SearchAction.callFilter(SearchAction.java:378)
         at sun.reflect.GeneratedMethodAccessor201.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:280)
         at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:220)
         at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:446)
         at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:266)
         at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1292)
         at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:510)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:6718)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
         at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
         at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3764)
         at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2644)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:219)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:178)
    >
    The above mentioned is coming several times , anybody please help out to get rid of this issue.
    Thanks in advance ,
    Krikar.

    This only tells you that the JVM is running out of heap space. It doesn't tell you what is causing the problem. You likely have a memory leak, but you could also try increasing the max heap size of the JVM (-Xmx command line option). It would help to watch the % mem in use statistic, but only immediately after a garbage collection cycle (you can force a GC from the admin console). If the % mem in use after the GC is increasing over time, then that likely confirms you have a memory leak. Note that looking at that statistic during the server startup probably is irrelevant. You'd need to wait until the server finishes starting up, and likely processed a few messages (to load static data).
    If you get to the point of confirming that you have a memory leak, that requires doing detailed analysis with a Java profiler (JProfiler, JProbe, YourKit, etc.) to track down the source of the leak.

  • Why we extends JFrame class in java

    Hello Java Developers,
    I am new to Java & Currently I am trying my hands on Java Swings.
    I wrote a very simple program in Java to display a JFrame on screen. My code is as follows:
    import javax.swing.*;
    public class JavaFrame {
    public static void main(String args[]){
    JFrame frame = new JFrame();
    frame.setTitle("My Frame");
    frame.setSize(400, 150);
    frame.setLocation(300, 300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    I saw some examples on internet & they are extending "JFrame" in their every example. I want to know what is the benefit of this ??? here is code:
    import javax.swing.*;
    public class JavaFrame extends JFrame {
    public static void main(String args[]){
    JFrame frame = new JFrame();
    frame.setTitle("My Frame");
    frame.setSize(400, 150);
    frame.setLocation(300, 300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    My second question is what is the meaning of line "frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);"
    frame - This object of class created by me.
    setDefaultCloseOperation() - This is predefined method in JFrame class.
    JFrame.EXIT_ON_CLOSE - what is the meaning of this ??

    I saw in JFrame API as you suggested & I found that
    EXIT_ON_CLOSE is an "public static final" method.Look again. It's not a method.
    final: this mehod must be executed
    am I right ???No. final means that the value cannot be reassigned.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db

  • How to create a new thread in display function -----Java OpenGL

    use netbean 6.1 to do this work.
    public void display(GLAutoDrawable drawable) {
          GL  gl = drawable.getGL();
          //I want to create a new thread here to draw an object
          Thread dt = new Thread(new DrawThread(gl,2),"Thread0");    //create a thread,DrawThread is a class I define
          //but it failed when compiling
          //are there any other ways or how to improve my method?
    }I want to do like this because I do not like to block the main thread when it is drawing an object

    Well, the autocode in your application is maintained by your autocode module, any attempt at changing it will result in having it reset back to the original autocode--that's one of the gotcha's about using autocode.
    Since it looks like you may not have the skills to do what you are asking and relying on the autocoder, you should probably start here:
    [Java Tutorial|http://java.sun.com/docs/books/tutorial/]
    And stay there until you are comfortable coding for yourself.

  • Multiple java threads in a JVM created by the invocation interface

    Hi,
    I have a certain application APP that calls functions of a C library. One of these functions creates a JVM through the invocation interface. In the JVM I create some other threads and a Swing GUI. From the java "main" thread as well as the other threads (including the Swing event dispatcher thread) I need to call dll functions through native java methods. The latter indirectly (through another dll) invoke functions of an API of application APP.
    I have problems when making calls from the java threads to the java native library. In some cases everything works well i.e., I'm able to make calls to the java native library from both the "main" java thread and the other threads. In other cases a crash occurs when attempting to access the native library from any threads but the "main" thread.
    Can anyone help me on this? Is there any requirement that only the main java thread makes callbacks to C code?
    Thanks.

    > why later sets of java application is taking longer?
    Probably because of CPU usage.  But could be memory.
    >Can I do something here so that later sets of apps also completes in 3 mins
    You tune the task, the complete task, to the box.  That means you must understand in detail what is taking time and then architect that to make the best use of the available CPUs and memory (and other resources as used by the task.)

  • Java.lang.OutOfMemoryError: unable to create new native thread on Win2000

    Dear all,
    I install a java server (SAP J2EE) on the windows machine and run into the following problem: the total number of threads cannot exceed 1200 (as i see this in the task manager)
    After it does reach this number no other tasks can be started. Thereafter i get java.lang.OutOfMemoryError: unable to create new native thread error .
    However the other machine where the same distribution of Win2000 Server is installed can easily coupe with more than 2500 theads. The same is true when the safe mode on the first machine is on: I can generate more than 1200 threads. So it seems the problem has something to do with Windows itself.
    I am really puzzled here, would really appreciate any help.
    Thanks in advance,
    Dimitry
    Surkov Dimitry
    [email protected]
    +49.1632.492618

    well, i do not supply any options when i start jvm, but it is not the course:
    it also happens with c programs. however in the safe mode it works. both for c and for java program.
    so it must be either some software (however memory is ok) or ...? i am lost. In some Unix system you can set the total number of threads allowed as an option in the kernal. But i guess this is not the case with windows.
    Thanks a lot for your reply,
    dimitry

  • To create a java class in Web dynpro

    Hi,
    I want to create a java class which can be used in multiple views. Where will i create it and how will i access it?
    Can i create the class in Comp controller's imeplementation between "begin others"----
    "end"?
    Any help?
    regards,
    Sujesh

    Hi,
      If you create the class within the begin others"----
    "end" section, this class will not be accessible by any other class.
      You can create a class in
    Project/src/packages/<namespace>/<your component>/<create a new subdirectory>/Test.java.
    This will be accessible to all other classes. Just make sure the first line of your java file is the proper package declaration. So in this case the 1st line dhould be:
    package <namespace>.<your component>.<subdirectory name>;
    Regards,
    Satyajit.

  • Exception in thread "main" java.lang.NoClassDefFoundError c:\MyClass/class

    i compile my java programm by typing javac c:\MyClass.java, i have 0 errors. But when i try to run the class file by typing java c:\MyClass.class i have this exception : Exception in thread "main" java.lang.NoClassDefFoundError c:\MyClass/class
    what is wrong please?

    what is wrong please? First, wrong forum. See the " New To Java Technology" forum.
    Second, you run classes not files (as the previous poster pointed out.)

  • Thread safe do-all class

    Hi,
    I'm new to Java programming and I've read through the forums and the numerous technical documents Sun has provided on how to make a GUI thread-safe. With what I've been able to understand, I created some template classes to handle the proper creation of JFrames, so I don't have to worry about playing with threads all the time. (I am operating under the assumption that invokeLater should handle the creation of all frames, not just the first window of the application).
    Since I'm not completely confident I've grasped the point, I was wondering if someone could look at this code to see if I've got the right idea. Your help would be much appreciated.
    Test.java
    import frames.*;
    public class Test
         public static void main(String args[])
              FrameOptions frameOpts = new FrameOptions("Options Window", 300, 400, true);
    frames\FrameOptions.java
    package frames;
    public class FrameOptions extends FrameTemplate
         public FrameOptions(String title, int width, int height, final boolean visible)
              super(title, width, height);
              javax.swing.SwingUtilities.invokeLater     (     new Runnable()
                                                 public void run()
                                                      createAndShow(visible);
         public void createAndShow(boolean visible)
              //Add all Swing components here.
              finishCreateAndShow(visible);
    frames\FrameTemplate.java
    package frames;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    public class FrameTemplate extends JFrame
         public FrameTemplate(String title)
              super(title);
         public FrameTemplate(String title, int width, int height)
              super(title);
              doSize(width, height);
         private void doSize(int width, int height)
              Dimension d = new Dimension(width, height);
              setMinimumSize(d);
              setPreferredSize(d);
         protected void finishCreateAndShow(boolean visible)
              pack();
              setVisible(visible);
    }

    OK, makes sense now.
    For anyone else who may be new and wondering about this, this can be summed up as follows.
    Summary 1:
    If you create new frames from things such as menu events, you do not need to use invokeLater. Events are automatically done in the GUI thread/event dispatching thread. But if you're spawning these things from main() (or anything else not running in the EDT), you do.
    If you're ever unsure of which thread a block of code is running in, just drop a System.out.println(javax.swing.SwingUtilities.isEventDispatchThread()); into it.
    Summary 2:
    Don't use those classes I wrote. They're rather pointless unless you're spawning all of your frames from main, which I suspect most people would not be doing.
    Thanks for the clarification.
    public static void main(String args[])
    is run in a separate thread (separate from the GUi
    i thread). So if you need to do painting or other
    swing stuff from inside the main method, just use an
    invoke later. If you create a new frame from the GUI
    thread, you don't need to invoke later. Only if you
    do it from the main method (or some other non-GUI
    thread). Hope that helps

  • How can I kill all Threads of the same class from within the run() method?

    Ok
    I have a class called Consumer that extends Thread
    I have several Consumer threans running... but, when a certain condition is true (within the run() method) in ANY of the threads, I want to kill ALL the threads of that object.
    is this possible?

    I know this is gonna be too demanding, but can someone please tell me why my Consumer's run() method never reaches the System.out.println( "ALL CONSUMING DONE") line
    Create a multi-threaded prime number calculator that is based on the producer-consumer model
    using semaphores. Your program should be able to check for prime numbers in a range specified
    by the user and with a variable number of threads. Example:
    $ java PrimeFind 3 5000 10000
    should use 1 producer and 2 consumers (3 threads in total, obviously the minimum is 2) to find all
    the prime numbers in the range [5000,10000].
    The producer should: use a buffer to store candidate numbers that have to be checked for
    primality.
    Consumers should: read from the buffer, check if a number is prime and update the status of the
    program accordingly (e.g. show the number on the screen, or save it to a file)
    import java.util.concurrent.Semaphore;
    import java.io.*;
    public class Assign1 {
    static int fromThisNumber;
    static int toThisNumber;
    static int numberOfThreads;
    static int buffer[];
    static Semaphore ready;          /*This semaphore is used by the Producer to signal
                                         an "OK" to the consumers*/
    static Semaphore critical;  /*This is a Mutex semaphore. It allows only 1 consumer
                                         to enter his critical section.
    static Semaphore counter;     /*This semaphore acts as a counter.
                                        Instead of having a global variable
                                         incremented each time, we just release()
                                         this semephore when we find a prime number
                                         Because remember that release() increments permits
    static Producer prod;
    static Consumer cons[];
    static int in=0;
    static int out=0;
    static PrintWriter outFile;
         public static void main (String args[]){
              try{
                   outFile=new PrintWriter(new FileWriter("primes.txt"));
                   }catch(Exception e){}
              numberOfThreads=Integer.parseInt(args[0]);
              fromThisNumber=Integer.parseInt(args[1]);
              toThisNumber=Integer.parseInt(args[2]);
              buffer=new int[Integer.parseInt(args[2])-Integer.parseInt(args[1])+1];
              ready=new Semaphore(0,false); /*We initialise it to 0 because we wait
                                                      for the Producer to produce atleast a
                                                      item. Suppose ready was 1 and if
                                                      Consumer ran first he would be in an
                                                      empty buffer */
              critical=new Semaphore (1,false);/*We initialise it to 1 because when
                                                         the first Consumer thread tries
                                                         to enter its critical section, it
                                                         should be allowed to;
                                                         Subsequent threads will have to
                                                         wait since only 1 thread can
                                                         access its critical section at a time*/
              counter=new Semaphore(0,false); // duh!
              cons=new Consumer[numberOfThreads-1]; /*numberOfThreads-1 because 1 thread
                                                                is taken by the Producer*/
              //Creating Producer object
              prod=new Producer();
              //Creating the Consumer object and start the thread.
              for(int i=0;i<cons.length;i++)
                        cons=new Consumer();
                        cons[i].start();
              prod.start();          
              //Printing to screen and file
    /*          for(int i=0;i<buffer.length;i++)
                   if(buffer[i]!=0)
                             System.out.println(buffer[i]);
                             outFile.println(buffer[i]);
              System.out.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits()+"\n primes.txt written");
              outFile.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits());
              outFile.close();*/                    
    static class Producer extends Thread {
         public void run(){try{
              while(in<buffer.length)     /*'in' should always be more than 'out'.Oherwise the consumer will try to access an empty index*/
                   {     System.out.println("producing");     
                        buffer[in]=fromThisNumber;
                        in++;
                        fromThisNumber++;
                        ready.release();
              catch (Exception e){e.printStackTrace();}
              System.out.println("ALL PRODUCING DONE");
    static class Consumer extends Thread {
         int tempout=0;
         public void run(){try{
              System.out.println("before while"+this.getId());
              while(tempout<=in)
                   System.out.println("before ready"+this.getId()+" "+ready.availablePermits()+" "+in);
                   ready.acquire();
                   System.out.println("before critical.acquire"+this.getId());
                   critical.acquire();
                   tempout=out;
                   out++;
                   critical.release();               
                   if(!isPrime(buffer[tempout]))
                        {System.out.println(buffer[tempout]+" by "+this.getId());buffer[tempout]=0;}
                   else {counter.release();System.out.println("prime added: "+buffer[tempout]+" by "+this.getId());}
                   critical.acquire();
                   tempout=out;
                   System.out.println("tempout:"+tempout+" of "+this.getId());
                   critical.release();
              System.out.println("ALL CONSUMING DONE"+this.getId());
         catch(Exception e){e.printStackTrace();}
         //Prime number-checking method     
         public boolean isPrime(int n){
              for(int i=2;i<=(n/2);i++)
                   if(n%i==0)
                        return false;
              return true;
    ======================
    import java.util.concurrent.Semaphore;
    import java.io.*;
    /* 3 questions to ask Barlas
    * Why error if I start the Consumer threads before Producer
    * Why does the counter semaphore always give a +1 result at the end
    * Is there a way I can verify that all the work is not being done by only 1 consumer thread? In other words, the workload is being shared properly
    * if I put ready.acquire() outside or inside the while loop, its not making any difference, why?
    * Strangely, its not making any difference if I playing with the release() and aquire() of the semaphores, WHY?!?!
    public class Assign1 {
    static int fromThisNumber;
    static int toThisNumber;
    static int numberOfThreads;
    static int buffer[];
    static Semaphore ready;          /*This semaphore is used by the Producer to signal
                                       an "OK" to the consumers*/
    static Semaphore critical; /*This is a Mutex semaphore. It allows only 1 consumer
                                       to enter his critical section.
    static Semaphore counter;     /*This semaphore acts as a counter.
                                  Instead of having a global variable
                                       incremented each time, we just release()
                                       this semephore when we find a prime number
                                       Because remember that release() increments permits
    static Producer prod;
    static Consumer cons[];
    static int in=0;
    static int out=0;
    static PrintWriter outFile;
         public static void main (String args[]){
              try{
                   outFile=new PrintWriter(new FileWriter("primes.txt"));
                   }catch(Exception e){}
              numberOfThreads=Integer.parseInt(args[0]);
              fromThisNumber=Integer.parseInt(args[1]);
              toThisNumber=Integer.parseInt(args[2]);
              buffer=new int[Integer.parseInt(args[2])-Integer.parseInt(args[1])+1];
              ready=new Semaphore(0,false); /*We initialise it to 0 because we wait
                                                      for the Producer to produce atleast a
                                                      item. Suppose ready was 1 and if
                                                      Consumer ran first he would be in an
                                                      empty buffer */
              critical=new Semaphore (1,false);/*We initialise it to 1 because when
                                                      the first Consumer thread tries
                                                      to enter its critical section, it
                                                      should be allowed to;
                                                      Subsequent threads will have to
                                                      wait since only 1 thread can
                                                      access its critical section at a time*/
              counter=new Semaphore(0,false); // duh!
              cons=new Consumer[numberOfThreads-1]; /*numberOfThreads-1 because 1 thread
                                                                is taken by the Producer*/
              //Creating Producer object
              prod=new Producer();
              //Creating the Consumer object and start the thread.
              for(int i=0;i<cons.length;i++)
                        cons[i]=new Consumer();
                        cons[i].start();
              prod.start();          
              //Printing to screen and file
    /*          for(int i=0;i<buffer.length;i++)
                   if(buffer[i]!=0)
                             System.out.println(buffer[i]);
                             outFile.println(buffer[i]);
              System.out.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits()+"\n primes.txt written");
              outFile.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits());
              outFile.close();*/                    
    static class Producer extends Thread {
         public void run(){try{
              while(in<buffer.length)     /*'in' should always be more than 'out'.Oherwise the consumer will try to access an empty index*/
                   {     System.out.println("producing");     
                        buffer[in]=fromThisNumber;
                        in++;
                        fromThisNumber++;
                        ready.release();
              catch (Exception e){e.printStackTrace();}
              System.out.println("ALL PRODUCING DONE");
    static class Consumer extends Thread {
         int tempout=0;
         public void run(){try{
              System.out.println("before while"+this.getId());
              while(tempout<=in)
                   System.out.println("before ready"+this.getId()+" "+ready.availablePermits()+" "+in);
                   ready.acquire();
                   System.out.println("before critical.acquire"+this.getId());
                   critical.acquire();
                   tempout=out;
                   out++;
                   critical.release();               
                   if(!isPrime(buffer[tempout]))
                        {System.out.println(buffer[tempout]+" by "+this.getId());buffer[tempout]=0;}
                   else {counter.release();System.out.println("prime added: "+buffer[tempout]+" by "+this.getId());}
                   critical.acquire();
                   tempout=out;
                   System.out.println("tempout:"+tempout+" of "+this.getId());
                   critical.release();
              System.out.println("ALL CONSUMING DONE"+this.getId());
         catch(Exception e){e.printStackTrace();}
         //Prime number-checking method     
         public boolean isPrime(int n){
              for(int i=2;i<=(n/2);i++)
                   if(n%i==0)
                        return false;
              return true;
    ===========================
    BTW, when I tried to change extends Thread to implements Runnable I got some kinda of error.
    Actually, my program is pretty complete... its just that something if messed up in my Consumer's run() method's while loop... I think
    I know guys its crazy to ask ya'll to look at so much code, but.... I'd really appreciate it. This assignment is killing me, been at it since 10 hours now....

  • Two threads in the same class ? Is that possible ?

    Hello, I am trying to use threads to move two images around the frame. And I am wondering if it is possible if it is possible to create two separate threads that act differently in the same class, for each of the image.
    Is just that so far I can't see a way since, by implementing Runnable, I'll need to overwrite the run() method. Which in a way just allows me to manage one image.
    Of course I can do two separate classes (each implementing Runnable) for each of the image, but since I think it may be an overkill, I rather to do it in just one.
    So, is that possible ?
    Thank you in advance.

    Of course I can do two separate classes (each implementing Runnable) for each of the image,Use two instances of the same class. Something like this example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=631379

  • How to terminate a java thread from c++ code?

    Hi,
    I made a screensaver which loads a jvm, forks a thread running a java class, wait until user's action(i.e. mouse move/click keyboard input), then terminate the java thread.
    However, I met a problem, How to terminate a running java thread from c++ code?
    Here is my code, but it does not work: (even after the terminate is called, jvm throws an error)
    JNIEnv* env;
    JavaVM* jvm;
    HANDLE hThread; //handle for the startThread
    unsigned __stdcall startThread(void *arg)
         jclass cls;
         jmethodID mainId;
         jint          res;
         int threadNum = (int)arg;
         res = jvm->AttachCurrentThread((void**)&env, NULL);
    cls = env->FindClass( MAIN_CLASS);
         mainId = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
         // setup the parameters to pass to main()
         jstring str;
         jobjectArray args;
         int i=0;
         args = env->NewObjectArray(1, env->FindClass("java/lang/String"), 0); //only one input parameters
         str = env->NewStringUTF("localhost");
         env->SetObjectArrayElement(args, 0, str);
         env->CallStaticVoidMethod(cls, mainId, args); // call main()      
         if (env->ExceptionOccurred()) {
                   env->ExceptionDescribe();
         return TRUE;
    Here is the main method:
    First create the jvm and load the thread. then tries to terminate the thread, but failed here
    switch (msg)
    { case WM_CREATE:
              JavaVMOption options[NUMBEROFOPTIONS];
              JavaVMInitArgs vmargs;     
              jint rc;
              vmargs.version = JNI_VERSION_1_4; /* version 1.4 */
              vmargs.options = options;
              vmargs.nOptions = NUMBEROFOPTIONS;
              vmargs.ignoreUnrecognized = JNI_FALSE;          
              rc=JNI_CreateJavaVM( &jvm, (void **)&env, &vmargs ); /* create JVM */
              /* We pass the thread number as the argument to the invoked thread */
              unsigned int threadId = -1;
              // to initialize a thread-safe C runtime library
              hThread = (HANDLE)_beginthreadex(NULL, 0, &startThread, NULL, 0, &threadId );
    } break;
    case (WM_DESTROY):
              CloseHandle( hThread );
              jvm->DestroyJavaVM(); /* kill JVM */
              Debug("Destroy Java Virtual Machine\n");
    }break;
    Note, after the thread "startThread" runs, it has an infinite loop and will not terminate, until the user clicks to terminate.(I didn't call jvm->DetachCurrentThread();_endthreadex(0); in the "startThread" because the java thread will not terminate by itself)
    Thus, the only way to terminate the thread is to call closehandle(hthread) in the main thread, which may cause jvm to throw an error.
    Do you know how to terminate a java thread safely???
    Thanks a lot

    Assuming that your java thread is in a loop of some kind. Such as
    int i=1; /* I tried using a boolean, I just could not get my C++ env, to change this value. So i decided to use an int */
    run {
    while(i)
    isdfjsdfj
    void seti()
    i=0
    So, B/4, i call destroyVM in my C++ code, i call this seti(). so the loop terminates, therefore my thread finishes executing and ends.
    Hope this helps
    tola.

  • Doubt in processing of  statements after calling JFrame class

    I have two java classes.
    The first one is Normal class and the second one is a JFrame class.
    In the first Class, i created an object for second JFrame class followed by a set of statements.
    Based on the input from the second class, i must process the statements, the problem i am facing is after creating the object for second frame class , the first class continues execution of the remaining statements. I must stop the execution of the statements until i get an input from the second class.
    How can i make the first class wait for an input from the second class.
    if possible provide me some source code.
    Thanks for your help!.

    Use a modal JDialog instead of a JFrame.
    db

  • Help! Unable to create new native thread

    Ok I see this problem all over the web but most of the posts are many years old and still leave me a little confused.  Often at random times on the same tags like CFLDAP I get the error "Unable to create new native thread".  Then a few minutes later the same tag on the same page works just fine.
    I have 4GB of memory in this box with 1400 MB set as the maximum Java heap size by the way.
    Here are my arguments from the jvm.config file.
    # Arguments to VM
    java.args=-server  -Xmx1400m -Dsun.io.useCanonCaches=false -XX:MaxPermSize=192m -XX:+UseParallelGC -Dcoldfusion.rootDir={application.home}/../ -Dcoldfusion.libPath={application.home}/../lib -Dcoldfusion.classPath={application.home}/../lib/updates,{application.home}/../lib,{appli cation.home}/../gateway/lib/,{application.home}/../wwwroot/WEB-INF/flex/jars,{application. home}/../wwwroot/WEB-INF/cfform/jars,"C:\\Program Files\\Apache Software Foundation\\Apache2.2\\htdocs\\InterWeb-Prod\\includes\\classes"
    Here is a typical error that comes through.
    struct     
    Browser     Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.70 Safari/533.4    
    DateTime    {ts '2010-06-23 10:07:44'}  
    Diagnostics unable to create new native thread null <br>The error occurred on line 122.
    GeneratedContent      
    HTTPReferer http://--------------------/index.cfm?FuseAction=HR.main    
    Mailto      interweb@--------------------- 
    Message     unable to create new native thread      
    QueryString fuseaction=ManagedLists.MailSubscriptions     
    RemoteAddress     192.168.250.124
    RootCause   struct    
    Message     unable to create new native thread      
    StackTrace          java.lang.OutOfMemoryError: unable to create new native thread at java.lang.Thread.start0(Native Method) at java.lang.Thread.start(Thread.java:597) at com.sun.jndi.ldap.Connection.<init>(Connection.java:208) at com.sun.jndi.ldap.LdapClient.<init>(LdapClient.java:112) at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2504) at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:263) at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:76) at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667) at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288) at javax.naming.InitialContext.init(InitialContext.java:223) at javax.naming.InitialContext.<init>(InitialContext.java:197) at javax.naming.directory.InitialDirContext.<init>(InitialDirContext.java:82) at coldfusion.tagext.net.LdapTag.do_ActionQuery(LdapTag.java:839) at coldfusion.tagext.net.LdapTag.doStartTag(LdapTag.java:616) at coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:2661) at cfadfunctions2ecfm1473603830$funcADLOOKUPUSERNAME.runFunction(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\includes\adfunctions.cfm:122) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:418) at coldfusion.runtime.UDFMethod$ArgumentCollectionFilter.invoke(UDFMethod.java:324) at coldfusion.filter.FunctionAccessFilter.invoke(FunctionAccessFilter.java:59) at coldfusion.runtime.UDFMethod.runFilterChain(UDFMethod.java:277) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:192) at coldfusion.runtime.CfJspPage._invokeUDF(CfJspPage.java:2471) at cfadfunctions2ecfm1473603830$funcADLOOKUPMULTIPLEUSERNAMES.runFunction(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\includes\adfunctions.cfm:54) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:418) at coldfusion.runtime.UDFMethod$ArgumentCollectionFilter.invoke(UDFMethod.java:324) at coldfusion.filter.FunctionAccessFilter.invoke(FunctionAccessFilter.java:59) at coldfusion.runtime.UDFMethod.runFilterChain(UDFMethod.java:277) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:192) at coldfusion.runtime.CfJspPage._invokeUDF(CfJspPage.java:2471) at cfdsp_managedlists2ecfm55598920.runPage(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\hr\managedlists\dsp_managedlists.cfm:232) at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:196) at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:370) at coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:2661) at cffbx_switch2ecfm2121232114.runPage(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\hr\managedlists\fbx_switch.cfm:23) at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:196) at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:370) at coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:2661) at cffbx_fusebox30_cf502ecfm1180471387._factor4(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\fbx_fusebox30_cf50.cfm:241) at cffbx_fusebox30_cf502ecfm1180471387._factor5(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\fbx_fusebox30_cf50.cfm:1) at cffbx_fusebox30_cf502ecfm1180471387.runPage(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\fbx_fusebox30_cf50.cfm:1) at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:196) at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:370) at coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:2661) at cfindex2ecfm749274359.runPage(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\index.cfm:23) at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:196) at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:370) at coldfusion.filter.CfincludeFilter.invoke(CfincludeFilter.java:65) at coldfusion.filter.ApplicationFilter.invoke(ApplicationFilter.java:273) at coldfusion.filter.RequestMonitorFilter.invoke(RequestMonitorFilter.java:48) at coldfusion.filter.MonitoringFilter.invoke(MonitoringFilter.java:40) at coldfusion.filter.PathFilter.invoke(PathFilter.java:86) at coldfusion.filter.ExceptionFilter.invoke(ExceptionFilter.java:70) at coldfusion.filter.ClientScopePersistenceFilter.invoke(ClientScopePersistenceFilter.java:2 8) at coldfusion.filter.BrowserFilter.invoke(BrowserFilter.java:38) at coldfusion.filter.NoCacheFilter.invoke(NoCacheFilter.java:46) at coldfusion.filter.GlobalsFilter.invoke(GlobalsFilter.java:38) at coldfusion.filter.DatasourceFilter.invoke(DatasourceFilter.java:22) at coldfusion.CfmServlet.service(CfmServlet.java:175) at coldfusion.bootstrap.BootstrapServlet.service(BootstrapServlet.java:89) at jrun.servlet.FilterChain.doFilter(FilterChain.java:86) at coldfusion.monitor.event.MonitoringServletFilter.doFilter(MonitoringServletFilter.java:42 ) at coldfusion.bootstrap.BootstrapFilter.doFilter(BootstrapFilter.java:46) at jrun.servlet.FilterChain.doFilter(FilterChain.java:94) at jrun.servlet.FilterChain.service(FilterChain.java:101) at jrun.servlet.ServletInvoker.invoke(ServletInvoker.java:106) at jrun.servlet.JRunInvokerChain.invokeNext(JRunInvokerChain.java:42) at jrun.servlet.JRunRequestDispatcher.invoke(JRunRequestDispatcher.java:286) at jrun.servlet.ServletEngineService.dispatch(ServletEngineService.java:543) at jrun.servlet.jrpp.JRunProxyService.invokeRunnable(JRunProxyService.java:203) at jrunx.scheduler.ThreadPool$DownstreamMetrics.invokeRunnable(ThreadPool.java:320) at jrunx.scheduler.ThreadPool$ThreadThrottle.invokeRunnable(ThreadPool.java:428) at jrunx.scheduler.ThreadPool$UpstreamMetrics.invokeRunnable(ThreadPool.java:266) at jrunx.scheduler.WorkerThread.run(WorkerThread.java:66)  
    I could really use some help figuring this out.  We are getting random errors a few times a day and usually in places where we are using CFLDAP.
    Thanks,
    David

    Absolutely unbelievable that this has been going on for 4 YEARS and there are still NO definitive answers from Adobe!!
    There's no definite answer from Adobe, because there's no definitive single question.  These errors come up because - for any number of possible reasons - the JVM becomes overloaded.  And it's almost always down to an issue with the application code being run, and nothing to do with CF, per-se.  So what's Adobe supposed to do?  Come and fix your application for you?  There are plenty of diagnostic tools out there - some built into CF itself - which you could use to sort the problem out.  Or you could hire someone like Mike Brunt to come and have a look at your set up.  All it takes to fix these things is to actually do something about fixing it, rather than slamming one's fist on the desk saying "why doesn't Adobe do something!"
    I thought - and my knowledge in the area isn't expansive - the inability to allocate threads was down to the app being choked up: threads are a finite commodity, and if requests are queuing up faster than the JVM can clear them, you're gonna get errors eventually.  What causes this sort of thing?  More traffic than the server can process.  This could be because of server kit, or it could be due to code that doesn't scale to the requirement.  Usually the latter.  Basically one cannot polish a turd.
    I have a 24x7 production server that services 180,000 clients in 300 countries around the clock that cannot afford to be down for more than a few minutes at a time.
    I'm running Windows 2008 32-bit with 4GB of RAM because I have some graphics software that cannot tolerate a 64-bit OS.  Everything has been running fine for the past few months, but now it's starting to crash more and more frequently.  I have CF 8.0.1.195765 and Java 1.6.0_04
    How many concurrent requests for 180000 clients generate?  The number of clients matters less than how heavily the site is used.  But, to be honest, I get the impression the implication is "it's a busy site", in which case I think your hardware is a bit on the lean side.  Also, if it's a mission-critical app, running it on a single server is probably ill-advised, just from a fault-tolerance perspective even before one starts thinking about performance.
    If I was in your situation, I'd consider the following options:
    * upgrade your JVM to the most recent version (1.6.0_21?)
    * put more RAM in the box, and run a second CF instance on it.
    * get another box.
    * refactor the environment so the graphics software runs on a different box, upgrading the CF server to 64-bit (again, with more RAM)
    * run some diagnostics on the server, seeing what's taking up threads and where any bottlenecks might be
    * get an expert in to do the analysis side of things.
    * stop expecting Adode to fix "something".
    One of my other symptoms I have noticed is that any work done using RDP starts getting really really bogged down.  Opening Windows Explorer and searching for files can take minutes.  Restarting the CF service will sometimes fail to complete, and you have to wait a few minutes before the manual Start option appears in the dropdown.  Maybe coincidentally, the Performance Monitor will fail to add any of the ColdFusion metrics, for example Running Requests and Queued Requests, and the Event Monitor shows an error relating to an 8-byte boundary not being maintained.
    You don't, by any chance, store your client variables in the registry do you?  The only time I've seen this happen is when the CF box is munging the OS environment, and the only way I can think this could happen if it was clogging the registry.  Never store client variables in the registry.
    Adam

Maybe you are looking for

  • Need some info on general question

    Hello everybody! This question for those who already works as a Java professional. I just don't have a clear picture of how can you apply java programming language in real working environment, in theory I can imagine, but I need a solid understanding

  • Tradiness in BPM Process

    Hi The transfer of 2000+ messages from ECC takes normal time, i.e. some minutes. But when the messages are directed to internal queue XBQO, in order to be processed in Process Engine, the problems start.  In the Process Engine task  WSXXXXXX the mess

  • Problem with buying Skype credit.

    I have tried to buy Skype credit several times, but no success. Everytime after I clicked the Continue button to make the purchase, it went to the page showing Loading and being frozen there. Any help would be appreciated.  

  • Using java.util.logging Properly

    Hello, I have implemented java.util.logging in my application by creating a kind of "wrapper" class that I call for handling logging. It doesn't extend the logging classes, it just provides an object with helper methods that I can call when I want it

  • TS3433 anyone using extended wifi on TimeCapsule 7.6.1 fw with BT router

    Just updated the firware on my TC to 7.6.1 and I now have problems with the TC wifi configured to extend the wifi from my BT router. These include flashing amber light on the TC, amber connection to the Internet in Airport Utility and general access