Thread vs Runnable

Hi All,
I know the basic difference between Thread and Runnable. If my class is extending some class but still we need to make it Thread, then we should use Runnable otherwise we can use any one.
But specifically I want to know is extending Thread gives any added advantage rather then implementing Runnable.
Please let me know the answer.
Regards,
Gourab

Pls refer to follwing link....
http://forum.java.sun.com/ann.jspa?annID=9
Hope you get your answer.
~ANil

Similar Messages

  • Difference bet Thread and Runnable Inteface

    what is the main difference bet Thread and Runnable interface. Where it is used Thread and Where it is used Runnable interface

    http://www.javaworld.com/javaworld/jw-04-1996/jw-04-threads.htmlThere are a lot of differences, see the article above for details.
    Generally, I would only extend Thread if I want to enhance/extend the functionality of how Threads work (like providing a Timer or a Clock, or something). If all I am doing is providing some work to be done in a separate thread, then I will create a class that implements Runnable and run it using new Thread(myRunnable).start(). Most of the time, I use Runnable, since rarely would I need to change how threads act.

  • Thread in runnable state

    I recently made my application from single threaded to multithreaded that sends emails after it gets details from DB about email address content etc.
    I primarily did this to send more mails concurrently. But I didn't see any performance improvement. After I took the stack trace couple of times I see all the threads are runnable but are not running. I understand JVM handles the switching of states, but I was wondering if I can go any further diagnosing what the problem is. It's a 2 CPU SunOS machine and I am spawning 3 threads.
    Stack Trace:
    1" prio=10 tid=0x0062cee8 nid=0x11 runnable [0xd347f000..0xd347fb70]
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:313)
    - locked <0xd8c77cb0> (a java.io.BufferedInputStream)
    at com.informix.asf.IfxDataInputStream.readFully(IfxDataInputStream.java:149)
    at com.informix.asf.IfxDataInputStream.readSmallInt(IfxDataInputStream.java:428)
    at com.informix.jdbc.IfxSqli.receiveMessage(IfxSqli.java:2177)
    at com.informix.jdbc.IfxSqli.sendStatementQuery(IfxSqli.java:1444)
    at com.informix.jdbc.IfxSqli.executeStatementQuery(IfxSqli.java:1383)
    at com.informix.jdbc.IfxSqli.executeStatementQuery(IfxSqli.java:1313)
    at com.informix.jdbc.IfxResultSet.executeQuery(IfxResultSet.java:216)
    at com.informix.jdbc.IfxStatement.executeQueryImpl(IfxStatement.java:839)
    at com.informix.jdbc.IfxPreparedStatement.executeQuery(IfxPreparedStatement.java:246)
    "0" prio=10 tid=0x0067ad18 nid=0x10 runnable [0xd357f000..0xd357faf0]
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:313)
    - locked <0xd8caa908> (a java.io.BufferedInputStream)
    at com.informix.asf.IfxDataInputStream.readFully(IfxDataInputStream.java:149)
    at com.informix.asf.IfxDataInputStream.readSmallInt(IfxDataInputStream.java:428)
    at com.informix.jdbc.IfxSqli.receiveMessage(IfxSqli.java:2177)
    at com.informix.jdbc.IfxSqli.sendStatementQuery(IfxSqli.java:1444)
    at com.informix.jdbc.IfxSqli.executeStatementQuery(IfxSqli.java:1383)
    at com.informix.jdbc.IfxSqli.executeStatementQuery(IfxSqli.java:1313)
    at com.informix.jdbc.IfxResultSet.executeQuery(IfxResultSet.java:216)
    at com.informix.jdbc.IfxStatement.executeQueryImpl(IfxStatement.java:839)
    at com.informix.jdbc.IfxPreparedStatement.executeQuery

    java.io is a blocking protocol.
    If you want to see improved performance you at least need to use java.nio.
    Even so, just allocating more threads will not make your program run faster.
    Unless your code can inherently use multiple-cpus, multiple threads will do you no good at all.
    Threads are useful for four things :
    1. Making people (or some other connected system) '*think*' you are doing multiple things at the same time, of course you are not doing so, the scheduler is just slicing up the cpu time and giving some to each thread. This is essentially "servicing a request within some acceptable amount of time", which is why you see a lot of thread usage on web servers.
    2. If you have a piece of code that can usefully divide work between two or more CPUs then threads can help you, even so allocating more threads than you have CPUs will not help, in fact your program will probably slow down (unless the threads are not doing anything at all.)
    3. The implementation of some algorithms can be easier to think about as a set of communicating processes, in which case you can use threads to achieve an implementation.
    4. Simulation : if you are simulating the interaction of objects in a complex system it can be useful to use threads in the simulation, but it does not necessarily run any faster, you are just using threads to help model the system.
    Most programs/programmers will be in category #1, as more multi-core / multi-cpu machine are deployed there will be pressure to move to category #2, but I think most people have a lot to learn about this subject.
    When attempting to achieve higher performance by using a mult-cpu machine, you need to think about how you define performance.
    It is better to measure "how much work" gets done in a fixed amount of time rather than measuring "how fast" your program is running, i.e. how much faster it executes a specific task.

  • Threads: implement runnable or extend Thread.  Which is better?

    I want to know which way is better, as I want to do some work in threads.
    Thanks,
    Virum

    I want to know which way is better, as I want to do
    some work in threads.
    Thanks,
    VirumOne reason for implementing runnable can be that java doesnot allow multiple inheritance so by implementing runnable you can, at the same time, extend another class.
    Another reason though not recommended and not good programming practice is that although you cannot restart a dead thread, if you use runnables, you can submit the old runnable instance to a new thread, thus practically starting a thread more than once.

  • Different output for each running(Thread or Runnable)

    When i run a program which extends Thread or implement Runnable interface, i get different output each time i run from either of the program. Why this can happen? Why the output from the program which extends Thread different from the output which implementing Runnable? i really can't figure out..can someone explain it to me?? thank you!! Belows are the program im trying to run..
    <code>
    public class RunThreads
         public static void main (String [] args)
              SomeThread p1 = new SomeThread(1);
              p1.start();
              SomeThread p2 = new SomeThread(2);
              p2.start();
              SomeThread p3 = new SomeThread(3);
              p3.start();
    } //end class RunThreads
    public class SomeThread extends Thread
         int myID;
         SomeThread(int id)
              this.myID = id;
         public void run()
              int i;
              for(i=1;i<11;i++)
              System.out.println("Thread" + myID + ": " + i);
    } //end class SomeThread
    </code>
    <code>
    public class RunThreads2
         public static void main (String [] args)
              Thread p1 = new Thread(new SomeThread2(1));
              p1.start();
              Thread p2 = new Thread(new SomeThread2(2));
              p2.start();
              Thread p3 = new Thread(new SomeThread2(3));
              p3.start();
    } //end class RunThreads2
    public class SomeThread2 implements Runnable
         int myID;
         SomeThread2(int id)
              this.myID = id;
         public void run()
              int i;
              for(i=1;i<11;i++)
              System.out.println("Thread" + myID + ": " + i);
    } //end class SomeThread2
    </code>

    Umm, could you explain the differences in the output first?

  • Thread and Runnable

    Can anyone please tell me why this code is not executing
    FirstClass second=new FirstClass("i m 2nd class");
         second.run();
    in the below program.
    its show the output like:
    i m 3rd class
    i m 4rd class
    i m in threadi m 3rd class 0
    i m 1st class
    i m runnablei m 1st class 0
    i m in threadi m 4rd class 0
    i m runnablei m 1st class 1
    i m in threadi m 3rd class 0
    i m runnablei m 1st class 2
    i m in threadi m 4rd class 0
    i m runnablei m 1st class 3
    i m in threadi m 3rd class 0
    i m runnablei m 1st class 4
    i m in threadi m 4rd class 0
    i m runnablei m 1st class 5
    i m in threadi m 3rd class 0
    i m runnablei m 1st class 6
    i m in threadi m 4rd class 0
    but it didnot tell me about 2nd runnable class why ?
    public class MainClass {
    public static void main(String[] args) {
         SecondClass third=new SecondClass("i m 3rd class");
         third.start();
         SecondClass fourth=new SecondClass("i m 4rd class");
         fourth.start();
         FirstClass first=new FirstClass("i m 1st class");
         first.run();
         FirstClass second=new FirstClass("i m 2nd class");
         second.run();
    class FirstClass implements Runnable{
         private int count;
         private String sq;
         public FirstClass(String str) {
              count=0;
              sq=str;
              System.out.println(str);
    public void run() {
         while(true){
         System.out.println("i m runnable" + sq+ " " +count);     
         try {
         count++;
    Thread.sleep(500);
         } catch (InterruptedException e) {
    class SecondClass extends Thread {
         private int count;
         private String sq;
         public SecondClass(String str) {
              count=0;
              sq=str;
              System.out.println(str);
    public void run() {
    while(true){
         System.out.println("i m in thread" + sq+ " " +count);
         try {
         Thread.sleep(1000);
         } catch (InterruptedException e) {
    }

    The reason behind this is that, whenever you implement Runnable in a class and invoke the run() method, no other threads can start after that call. So when you invoke first.run(), the thread "i m 2nd class" doesn't start, i.e,
    SecondClass third=new SecondClass("i m 3rd class");
    third.start();
    SecondClass fourth=new SecondClass("i m 4rd class");
    fourth.start();
    FirstClass first=new FirstClass("i m 1st class");
    first.run();
    // this thread won't start and hence the result
    FirstClass second=new FirstClass("i m 2nd class");
    second.run();
    If you had called the run() at the beginning of the program, then neither of the threads would have started
    FirstClass first=new FirstClass("i m 1st class");
    first.run();
    // none of the threads would start
    SecondClass third=new SecondClass("i m 3rd class");
    third.start();
    SecondClass fourth=new SecondClass("i m 4rd class");
    fourth.start();
    FirstClass second=new FirstClass("i m 2nd class");
    second.run();
    and that's the reason for your output!

  • Thread state; "runnable"; what is it mean ?

    Hi All,
    could somebody please explain:
    what does all the thread states exactly mean?
    a more specific question:
    there is a thread state called "runnable" ....what does this state exactly means?
    i mean does it mean this thread is "running" OR is it "about" to run.
    OR this thread state means: what it can do, not what it is doing.
    Please explain.
    thanks, sangita

    Wrong. A thread in a runnable state may not be running. It could be, but mearly by being in the
    Runnable state does not force it to be running. Calling thread.start() schedules the thread to run.
    Therefore runnable means it could be running or it could be ready to run. You are using "running" as "using CPU".
    I was using "running" in the sense of the Sun's tutorial in pointed to.
    From the tutorial:
    "After the start method has returned, the thread is "running". Yet, it's somewhat more complex than that. As the previous figure shows, a thread that has been started is actually in the Runnable state. Many computers have a single processor, thus making it impossible to run all "running" threads at the same time. The Java runtime system must implement a scheduling scheme that shares the processor between all "running" threads. (See Understanding Thread Priority for more information about scheduling.) So at any given time, a "running" thread actually may be waiting for its turn in the CPU. "

  • Setting Priority Of A Thread With An Internal Runnable

    Im creating a few thread using the technique of embedding the actual runnable within the Threads constructor like below:
    new Thread(new Runnable()
         public void run()
              long start_t1 = System.currentTimeMillis();
              bruteforce();
              long finished_t1 = System.currentTimeMillis();
              timetaken_t1 = (finished_t1 - start_t1);
                 t1_finished = true;
              if(finished())scoreBoard();
    ).start();the problem im having is that I want to assign priorities to these threads. The two usual techniques:
    Threadname.MIN_PRIORITY
    or
    Threadname.setPriority(5);
    Won't work because in this technique you cannot assign the thread a name like
    Thread t = new Thread(new Runnable() ....Should I not be able to use this.setPriority(5) or this.MIN_PRIORITY? They don't seem to be working for me, however maybe im placing them in the wrong place.
    Any help would be great, Im really stuck for time on this one!

    Above should work, or if you want you could just assign a variable to the thread.
    final Thread t = {...}And use t call the thread methods.

  • Problem with threads and camera.

    Hi everybody!
    I've a problem with taking snapshot.
    I would like to display a loading screen after it take snapshot ( sometimes i
    have to wait few seconds after i took snapshot. Propably photo is being taken in time where i have to wait).
    I was trying to use threads but i didn't succeed.
    I made this code:
    display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while((!performing.isShown()) && (backgroundCamera.isShown())){
                        Thread.yield();
                    notifyAll();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        this.wait();                   
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();This code is sometimes showing performing screen but sometimes no.
    I don't know why. In my opinion performing.isShown() method isn't working correctly.
    Does anyone have some idea how to use threads here?

    Hi,
    I've finally managed to work this fine.
    The code:
           Object o = new Object();
           display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while(!performing.isShown()){
                        Thread.yield();
                   synchronized(o) {
                      o.notify();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        synchronized(o) {
                           o.wait(1);
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();

  • Error in threading

    On clicking browse I am getting
    [bold]Warning:[bold] To avoid potential deadlock, operations that may block, such as
    networking, should be performed in a different thread than the
    commandAction() handler.
    Can anybody help?
    for the following code
    * MailAttachmentMidlet.java
    * Created on September 18, 2007, 12:53 PM
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Enumeration;
    import javax.microedition.io.Connector;
    import javax.microedition.io.HttpConnection;
    import javax.microedition.io.file.FileConnection;
    import javax.microedition.io.file.FileSystemRegistry;
    import javax.microedition.lcdui.Alert;
    import javax.microedition.lcdui.AlertType;
    import javax.microedition.lcdui.Choice;
    import javax.microedition.lcdui.ChoiceGroup;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.List;
    import javax.microedition.lcdui.StringItem;
    import javax.microedition.lcdui.TextBox;
    import javax.microedition.lcdui.TextField;
    import javax.microedition.midlet.*;
    * @author  Sudipa
    * @version
    public class MailAttachmentMidlet extends MIDlet implements CommandListener,Runnable{
        String encodedData;
        HttpConnection conn;
       // Form mailform;
        private TextBox textattach;
        private String type=new String();
        private String agent=new String() ;
        private Display display;
        private static final String boundary = "-----------------------------" + Long.toString(System.currentTimeMillis(), 16);
        private static final String url=new String("http://localhost:8084/test/Upload2.jsp");
        private static final String[] attrList = { "Read", "Write", "Hidden" };
        private static final String[] typeList = { "Regular File", "Directory" };
        private static final String[] monthList =
            { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
        /* special string denotes upper directory */
        private static final String UP_DIRECTORY = "..";
        /* special string that denotes upper directory accessible by this browser.
         * this virtual directory contains all roots.
        private static final String MEGA_ROOT = "/";
        /* separator string as defined by FC specification */
        private static final String SEP_STR = "/";
        /* separator character as defined by FC specification */
        private static final char SEP = '/';
        private String currDirName;
        private Command upload = new Command("Upload", Command.ITEM, 1);
        private Command browse = new Command("Browse", Command.ITEM, 1);
        private Command view = new Command("View", Command.ITEM, 1);
        private Command prop = new Command("Properties", Command.ITEM, 2);
        private Command back = new Command("Back", Command.BACK, 2);
        private Command exit = new Command("Exit", Command.EXIT, 3);
        private TextField nameInput; // Input field for new file name
        private ChoiceGroup typeInput; // Input field for file type (regular/dir)
        private Image dirIcon;
        private Image fileIcon;
        private Image[] iconList;
        public MailAttachmentMidlet()
               //  encodedData=(" Content-Type: image/png�PNG  IHDR��asRGB���gAMA�? �a cHRMz&�����u0�`:�p��Q</IDAT8OE��o�Q��$������������%�? $V��\"!B$?h��/��SU�1>���L��L;)-������aA�P�����7���{�y�s���$�sR���+���/.�x��q���%6��~�]*w�I?I�1r���q?i�:��qxrN*B)��X�I�vJ�I�L�Pkp���r0��8k��4��������w��� �N��R���=��A ���^�0'����-������1�k?��I#{ ��r�'�?S�(�I|��?�Om��08�-4���R�Z�w?�\/M���� ��&ip�4��i��,�3�����7h��[x�]���7X����Mg�� �����?�.C'\MH_ ��;>^�,��^���;5�h�F.r��uHn�.�{��t��|+`���.3�?,q�@fM��J�{���!?�����hcb�s|{j?��U�G�h�>?��Yg?���������F���`�� ��9�-�v?���F������r0 &�JL���2G�%��4����> q��&y�D�� :���M����`b�L@�Ol�%���u�IEND�B`�");
        public synchronized byte[] getData(String filename)
        { byte[] b=null;
        try{
          System.out.println("file:///"+filename);
          FileConnection fc = (FileConnection)Connector.open("file:///"+filename);
          //  FileConnection fc = (FileConnection)Connector.open("file://e:/images/"+filename); 
             if(!fc.exists()) {
               Alert alert=new Alert("File do not exist");
               alert.setTimeout(Alert.FOREVER);
              display.setCurrent(alert);
             InputStream is = fc.openInputStream();
             b= new byte[(int)fc.fileSize()];
             int length = is.read(b, 0, (int)fc.fileSize());
             System.out.println
                ("Content of "+filename + ": "+ new String(b, 0, length));
          } catch (Exception e) {
             Alert alert=new Alert(e.getMessage());
               alert.setTimeout(Alert.FOREVER);
              display.setCurrent(alert);
          finally{
              return b;
    //          Enumeration filelist = fc.list("*", true);
        public void startApp() {
          startThread(); 
        public void pauseApp() {
         public void destroyApp(boolean unconditional) {
         * Show file list in the current directory .
        void showCurrDir() {
            Enumeration e;
            FileConnection currDir = null;
            List browser;
            try {
                if (MEGA_ROOT.equals(currDirName)) {
                    e = FileSystemRegistry.listRoots();
                    browser = new List(currDirName, List.IMPLICIT);
                } else {
                    currDir = (FileConnection)Connector.open("file://localhost/" + currDirName);
                    e = currDir.list();
                    browser = new List(currDirName, List.IMPLICIT);
                    // not root - draw UP_DIRECTORY
                    browser.append(UP_DIRECTORY, dirIcon);
                while (e.hasMoreElements()) {
                    String fileName = (String)e.nextElement();
                    if (fileName.charAt(fileName.length() - 1) == SEP) {
                        // This is directory
                        browser.append(fileName, dirIcon);
                    } else {
                        // this is regular file
                        browser.append(fileName, fileIcon);
                browser.setSelectCommand(view);
                //Do not allow creating files/directories beside root
                if (!MEGA_ROOT.equals(currDirName)) {
                    browser.addCommand(prop);
    //                browser.addCommand(creat);
    //                browser.addCommand(delete);
                browser.addCommand(exit);
                browser.setCommandListener(this);
                if (currDir != null) {
                    currDir.close();
                Display.getDisplay(this).setCurrent(browser);
            } catch (IOException ioe) {
                ioe.printStackTrace();
        void traverseDirectory(String fileName) {
            /* In case of directory just change the current directory
             * and show it
            if (currDirName.equals(MEGA_ROOT)) {
                if (fileName.equals(UP_DIRECTORY)) {
                    // can not go up from MEGA_ROOT
                    return;
                currDirName = fileName;
            } else if (fileName.equals(UP_DIRECTORY)) {
                // Go up one directory
                // TODO use setFileConnection when implemented
                int i = currDirName.lastIndexOf(SEP, currDirName.length() - 2);
                if (i != -1) {
                    currDirName = currDirName.substring(0, i + 1);
                } else {
                    currDirName = MEGA_ROOT;
            } else {
                currDirName = currDirName + fileName;
            showCurrDir();
        void showFile(String fileName) {
            try {
                FileConnection fc =
                    (FileConnection)Connector.open("file://localhost/" + currDirName + fileName);
                if (!fc.exists()) {
                    throw new IOException("File does not exists");
                InputStream fis = fc.openInputStream();
                byte[] b = new byte[1024];
                int length = fis.read(b, 0, 1024);
                fis.close();
                fc.close();
                TextBox viewer =
                    new TextBox("View File: " + fileName, null, 1024,
                        TextField.ANY | TextField.UNEDITABLE);
                viewer.addCommand(back);
                viewer.addCommand(exit);
                viewer.setCommandListener(this);
                if (length > 0) {
                    viewer.setString(new String(b, 0, length));
                Display.getDisplay(this).setCurrent(viewer);
            } catch (Exception e) {
                Alert alert =
                    new Alert("Error!",
                        "Can not access file " + fileName + " in directory " + currDirName +
                        "\nException: " + e.getMessage(), null, AlertType.ERROR);
                alert.setTimeout(Alert.FOREVER);
                Display.getDisplay(this).setCurrent(alert);
    void showProperties(String fileName) {
            try {
                if (fileName.equals(UP_DIRECTORY)) {
                    return;
                FileConnection fc =
                    (FileConnection)Connector.open("file://localhost/" + currDirName + fileName);
                if (!fc.exists()) {
                    throw new IOException("File does not exists");
                Form props = new Form("Properties: " + fileName);
                ChoiceGroup attrs = new ChoiceGroup("Attributes:", Choice.MULTIPLE, attrList, null);
                attrs.setSelectedFlags(new boolean[] { fc.canRead(), fc.canWrite(), fc.isHidden() });
                props.append(new StringItem("Location:", currDirName));
                props.append(new StringItem("Type: ", fc.isDirectory() ? "Directory" : "Regular File"));
                props.append(new StringItem("Modified:", myDate(fc.lastModified())));
                props.append(attrs);
                props.addCommand(back);
                props.addCommand(exit);
                props.setCommandListener(this);
                fc.close();
                Display.getDisplay(this).setCurrent(props);
            } catch (Exception e) {
                Alert alert =
                    new Alert("Error!",
                        "Can not access file " + fileName + " in directory " + currDirName +
                        "\nException: " + e.getMessage(), null, AlertType.ERROR);
                alert.setTimeout(Alert.FOREVER);
                Display.getDisplay(this).setCurrent(alert);
       private String myDate(long time) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date(time));
            StringBuffer sb = new StringBuffer();
            sb.append(cal.get(Calendar.HOUR_OF_DAY));
            sb.append(':');
            sb.append(cal.get(Calendar.MINUTE));
            sb.append(':');
            sb.append(cal.get(Calendar.SECOND));
            sb.append(',');
            sb.append(' ');
            sb.append(cal.get(Calendar.DAY_OF_MONTH));
            sb.append(' ');
            sb.append(monthList[cal.get(Calendar.MONTH)]);
            sb.append(' ');
            sb.append(cal.get(Calendar.YEAR));
            return sb.toString();
      public void run()
        display=Display.getDisplay(this);
    //        mailform= new Form("Attachment");
            textattach=new TextBox("Attachment","",100,TextField.ANY);
            upload=new Command("Upload",Command.SCREEN,1);
    //        mailform.append(textattach);
            textattach.addCommand(upload);
            textattach.addCommand(browse);
            textattach.setCommandListener(this);
            display.setCurrent(textattach); 
      public void startThread()
                Thread th=new Thread(this);
                th.run();
        public void commandAction(Command command,Displayable displayable)
            if(command==browse)
               currDirName = MEGA_ROOT;
            try {
                dirIcon = Image.createImage("/icons/dir.png");
            } catch (IOException e) {
                dirIcon = null;
            try {
                fileIcon = Image.createImage("/icons/file.png");
            } catch (IOException e) {
                fileIcon = null;
            iconList = new Image[] { fileIcon, dirIcon };
            try {
                showCurrDir();
            } catch (SecurityException e) {
                Alert alert =
                    new Alert("Error", "You are not authorized to access the restricted API", null,AlertType.ERROR);
                alert.setTimeout(Alert.FOREVER);
                Form form = new Form("Cannot access FileConnection");
                form.append(new StringItem(null,"You cannot run this MIDlet with the current permissions. Sign the MIDlet suite, or run it in a different security domain"));
                form.addCommand(exit);
                form.setCommandListener(this);
                Display.getDisplay(this).setCurrent(alert, form);
            } catch (Exception e) {
                e.printStackTrace();
         else   if(command==upload)
               if(!textattach.getString().equals(""))
             {try {type=new String("image/png");
               encodedData=new String(getData(textattach.getString()));  
                conn = (HttpConnection) Connector.open( url,Connector.READ_WRITE );
                conn.setRequestMethod( HttpConnection.POST );
    //          conn.setRequestProperty( "User-Agent", agent );
                conn.setRequestProperty( "Content-Type", type );
                conn.setRequestProperty( "Content-Length",new Integer(encodedData.length()).toString());
                OutputStream os = conn.openOutputStream();         
                System.out.println("success");
                String HeaderStr=boundary+new String(" Content-Disposition: form-data; name=\"uname\" fsdgfs ")+boundary+new String(" Content-Disposition: form-data; name=\"upfile\"; filename=\"_suite_8.png\" Content-Type: image/png");
                String FooterStr=new String(" ")+boundary+new String("--")+new String("\r\n");
                System.out.println((HeaderStr+""+ encodedData.trim()+FooterStr).getBytes());
                os.write((HeaderStr+""+ encodedData+FooterStr).getBytes());
                os.close();
                int rc = conn.getResponseCode();
               textattach.setString("");
            } catch (IOException ex) {
               Alert alert=new Alert(ex.getMessage());
               alert.setTimeout(Alert.FOREVER);
              display.setCurrent(alert);
        }else if (command == view) {
                List curr = (List)displayable;
                final String currFile = curr.getString(curr.getSelectedIndex());
                new Thread(new Runnable() {
                        public void run() {
                            if (currFile.endsWith(SEP_STR) || currFile.equals(UP_DIRECTORY)) {
                                traverseDirectory(currFile);
                            } else {
                                // Show file contents
                                showFile(currFile);
                    }).start();
            } else if (command == prop) {
                List curr = (List)displayable;
                String currFile = curr.getString(curr.getSelectedIndex());
                showProperties(currFile);
         else if (command == back) {
                showCurrDir();
            } else if (command == exit) {
                destroyApp(false);
    //        else if (command == delete) {
    //            List curr = (List)d;
    //            String currFile = curr.getString(curr.getSelectedIndex());
    //            executeDelete(currFile);
    }

    {color:#000080}This article explains it far better than I could even attempt to ;-){color}
    http://developers.sun.com/mobility/midp/articles/threading/
    {color:#000080}db{color}

  • A lot of threads getting created on weblogic 10.3.2

    Hi here is the thread dump.
    can you help me in solving this
    Full thread dump Java HotSpot(TM) Server VM (14.0-b16 mixed mode):
    "scheduledJobsListenerContainer-55" prio=6 tid=0x4e7aac00 nid=0x2fac waiting on condition [0x51aaf000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
         at java.lang.Thread.sleep(Native Method)
         at org.springframework.jms.listener.DefaultMessageListenerContainer.sleepInbetweenRecoveryAttempts(DefaultMessageListenerContainer.java:837)
         at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:891)
         at java.lang.Thread.run(Thread.java:619)
    Locked ownable synchronizers:
         - None
    "scheduledJobsListenerContainer-53" prio=6 tid=0x4cfa1c00 nid=0x2d38 waiting on condition [0x51d2f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
         at java.lang.Thread.sleep(Native Method)
         at org.springframework.jms.listener.DefaultMessageListenerContainer.sleepInbetweenRecoveryAttempts(DefaultMessageListenerContainer.java:837)
         at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:891)
         at java.lang.Thread.run(Thread.java:619)
    Locked ownable synchronizers:
         - None
    "processQueueListenerContainer-56" prio=6 tid=0x5224ec00 nid=0x26b4 waiting on condition [0x517df000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
         at java.lang.Thread.sleep(Native Method)
         at org.springframework.jms.listener.DefaultMessageListenerContainer.sleepInbetweenRecoveryAttempts(DefaultMessageListenerContainer.java:837)
         at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:891)
         at java.lang.Thread.run(Thread.java:619)
    Locked ownable synchronizers:
         - None
    "processQueueListenerContainer-52" prio=6 tid=0x4f0af000 nid=0x2c34 waiting on condition [0x5191f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
         at java.lang.Thread.sleep(Native Method)
         at org.springframework.jms.listener.DefaultMessageListenerContainer.sleepInbetweenRecoveryAttempts(DefaultMessageListenerContainer.java:837)
         at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:891)
         at java.lang.Thread.run(Thread.java:619)
    Locked ownable synchronizers:
         - None
    "processQueueListenerContainer-56" prio=6 tid=0x4db7c000 nid=0x2ad0 waiting on condition [0x5182f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
         at java.lang.Thread.sleep(Native Method)
         at org.springframework.jms.listener.DefaultMessageListenerContainer.sleepInbetweenRecoveryAttempts(DefaultMessageListenerContainer.java:837)
         at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:891)
         at java.lang.Thread.run(Thread.java:619)
    Locked ownable synchronizers:
         - None
    "scheduledJobsListenerContainer-52" prio=6 tid=0x4db7c800 nid=0x2948 waiting on condition [0x514bf000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
         at java.lang.Thread.sleep(Native Method)
         at org.springframework.jms.listener.DefaultMessageListenerContainer.sleepInbetweenRecoveryAttempts(DefaultMessageListenerContainer.java:837)
         at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:891)
         at java.lang.Thread.run(Thread.java:619)
    Locked ownable synchronizers:
         - None
    "scheduledJobsListenerContainer-56" prio=6 tid=0x4ea4f800 nid=0x15fc waiting on condition [0x56e5f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
         at java.lang.Thread.sleep(Native Method)
         at org.springframework.jms.listener.DefaultMessageListenerContainer.sleepInbetweenRecoveryAttempts(DefaultMessageListenerContainer.java:837)
         at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:891)
         at java.lang.Thread.run(Thread.java:619)
    Locked ownable synchronizers:
         - None
    "processQueueListenerContainer-53" prio=6 tid=0x4d854400 nid=0x2e38 waiting on condition [0x5196f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
         at java.lang.Thread.sleep(Native Method)
         at org.springframework.jms.listener.DefaultMessageListenerContainer.sleepInbetweenRecoveryAttempts(DefaultMessageListenerContainer.java:837)
         at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:891)
         at java.lang.Thread.run(Thread.java:619)
    Locked ownable synchronizers:
         - None
    "RMI TCP Connection(2)-" daemon prio=6 tid=0x4f365400 nid=0x2d88 runnable [0x51f0f000]
    java.lang.Thread.State: RUNNABLE
         at java.net.SocketInputStream.socketRead0(Native Method)
         at java.net.SocketInputStream.read(SocketInputStream.java:129)
         at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
         at java.io.BufferedInputStream.read(BufferedInputStream.java:237)
         - locked <0x04f9bfd0> (a java.io.BufferedInputStream)
         at java.io.FilterInputStream.read(FilterInputStream.java:66)
         at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:517)
         at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
         at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
         at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
         at java.lang.Thread.run(Thread.java:619)
    Locked ownable synchronizers:
         - <0x04ec0ac0> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
    "JMX server connection timeout 144853" daemon prio=6 tid=0x4d204c00 nid=0x2940 in Object.wait() [0x51ebf000]
    java.lang.Thread.State: TIMED_WAITING (on object monitor)
         at java.lang.Object.wait(Native Method)
         - waiting on <0x04f41500> (a [I)
         at com.sun.jmx.remote.internal.ServerCommunicatorAdmin$Timeout.run(ServerCommunicatorAdmin.java:150)
         - locked <0x04f41500> (a [I)
         at java.lang.Thread.run(Thread.java:619)
    Locked ownable synchronizers:
         - None
    "RMI Scheduler(0)" daemon prio=6 tid=0x4d98c800 nid=0x2a3c waiting on condition [0x51dcf000]
    java.lang.Thread.State: TIMED_WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for <0x04d4d8b8> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:198)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:1963)
         at java.util.concurrent.DelayQueue.take(DelayQueue.java:164)
         at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:583)
         at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:576)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
         at java.lang.Thread.run(Thread.java:619)
    Locked ownable synchronizers:
         - None
    "RMI TCP Connection(1)-" daemon prio=6 tid=0x4d98c400 nid=0x24d4 runnable [0x51d7f000]
    java.lang.Thread.State: RUNNABLE
         at java.net.SocketInputStream.socketRead0(Native Method)
         at java.net.SocketInputStream.read(SocketInputStream.java:129)
         at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
         at java.io.BufferedInputStream.read(BufferedInputStream.java:237)
         - locked <0x04ece968> (a java.io.BufferedInputStream)
         at java.io.FilterInputStream.read(FilterInputStream.java:66)
         at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:517)
         at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
         at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
         at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
         at java.lang.Thread.run(Thread.java:619)
    Edited by: user8676157 on Jun 25, 2010 12:22 PM
    Edited by: user8676157 on Jun 25, 2010 12:23 PM

    It seems a bug. Apply the latest patchset and see this doc:
    ID 1099499.1
    regards

  • Event Dispatch Thread Hangs, what is wrong?

    The Event Dispatch Thread Hangs when showing a modal dialog while running a
    SwingWorker Thread.
    I have included my code at the bottom of the page. There are three classes. I have posted a bug report to red hat. But I want to make sure my code is correct.
    My test case just puts the SwingWorker to sleep
    but the problem occurs if I do something real, like connect to a database, etc.
    Also I have tried little different variations of the logic calling
    setVisible(true)/(false) in different places and the same problem occurs.
    It seems to work with Sun JDK, note I am using IcedTea with Fedora Core 8.
    Version-Release number of selected component (if applicable):
    [szakrews@tuxtel ~]$ java -version
    java version "1.7.0"
    IcedTea Runtime Environment (build 1.7.0-b21)
    IcedTea Client VM (build 1.7.0-b21, mixed mode)How reproducible:
    Every couple times.
    javac TestClass2
    java TestClass2eventually it will hang. If it doesn't try again.
    You don't have to wait for the program to finish either.
    The program runs the Dialog 10 times but it never works or fails in the middle, it will either work or fail from the first dialog displayed.
    I have included a thread dump. That is about the most informative information I can get. Neither tracing nor writing a custom ThreadQueue or Drawing Manager to trace events produces any helpful information.
    Actual results:
    The JProccessBar won't move, and the SwingWorker finishes but the done() method is never run. The PROGRAM is not hung however because if I close the dialog then it will continue.
    Expected results:
    The JProccessBar should always move and the SwingWorker should always run the done() method.
    Additional info:
    java thread dump after freeze, taken with kill -s SIGQUIT <pid>
    2008-06-25 12:25:50
    Full thread dump IcedTea Client VM (1.7.0-b21 mixed mode):
    "DestroyJavaVM" prio=10 tid=0x938afc00 nid=0x1419 waiting on condition
    [0x00000000..0x0018a074]
       java.lang.Thread.State: RUNNABLE
    "AWT-EventQueue-0" prio=10 tid=0x938ae400 nid=0x1429 in Object.wait()
    [0x07f96000..0x07f96f04]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x96748f80> (a java.awt.EventQueue)
            at java.lang.Object.wait(Object.java:503)
            at java.awt.EventQueue.getNextEvent(EventQueue.java:485)
            - locked <0x96748f80> (a java.awt.EventQueue)
            at
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:248)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:201)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:195)
            at java.awt.Dialog$1.run(Dialog.java:1073)
            at java.awt.Dialog$3.run(Dialog.java:1127)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.awt.Dialog.show(Dialog.java:1125)
            at java.awt.Component.show(Component.java:1456)
            at java.awt.Component.setVisible(Component.java:1408)
            at java.awt.Window.setVisible(Window.java:871)
            at java.awt.Dialog.setVisible(Dialog.java:1012)
            at net.xtel.production.WaitDialog.showWaitDialog(WaitDialog.java:72)
            at net.xtel.production.WaitDialog.showWaitDialog(WaitDialog.java:102)
            at TestClass2.showWait(TestClass2.java:79)
            at TestClass2.createAndShowGUI(TestClass2.java:126)
            at TestClass2.access$0(TestClass2.java:114)
            at TestClass2$3.run(TestClass2.java:138)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:227)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:603)
            at
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:276)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:201)
            at
    java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:191)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:186)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:178)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:139)
    "AWT-Shutdown" prio=10 tid=0x938ad000 nid=0x1428 in Object.wait()
    [0x03ea7000..0x03ea7f84]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x96749268> (a java.lang.Object)
            at java.lang.Object.wait(Object.java:503)
            at sun.awt.AWTAutoShutdown.run(AWTAutoShutdown.java:281)
            - locked <0x96749268> (a java.lang.Object)
            at java.lang.Thread.run(Thread.java:675)
    "AWT-XAWT" daemon prio=10 tid=0x938a8400 nid=0x1423 runnable
    [0x02ccc000..0x02ccd104]
       java.lang.Thread.State: RUNNABLE
            at sun.awt.X11.XToolkit.waitForEvents(Native Method)
            at sun.awt.X11.XToolkit.run(XToolkit.java:550)
            at sun.awt.X11.XToolkit.run(XToolkit.java:525)
            at java.lang.Thread.run(Thread.java:675)
    "Java2D Disposer" daemon prio=10 tid=0x93854000 nid=0x1421 in Object.wait()
    [0x07aea000..0x07aead84]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e7010> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
            - locked <0x966e7010> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:150)
            at sun.java2d.Disposer.run(Disposer.java:143)
            at java.lang.Thread.run(Thread.java:675)
    "Low Memory Detector" daemon prio=10 tid=0x93c15000 nid=0x141f runnable
    [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "CompilerThread0" daemon prio=10 tid=0x93c13400 nid=0x141e waiting on condition
    [0x00000000..0x03a8a954]
       java.lang.Thread.State: RUNNABLE
    "Signal Dispatcher" daemon prio=10 tid=0x93c11c00 nid=0x141d waiting on
    condition [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "Finalizer" daemon prio=10 tid=0x095e7000 nid=0x141c in Object.wait()
    [0x005d2000..0x005d3004]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e71d8> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
            - locked <0x966e71d8> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:150)
            at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:177)
    "Reference Handler" daemon prio=10 tid=0x095e2400 nid=0x141b in Object.wait()
    [0x00581000..0x00582084]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e7260> (a java.lang.ref.Reference$Lock)
            at java.lang.Object.wait(Object.java:503)
            at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:134)
            - locked <0x966e7260> (a java.lang.ref.Reference$Lock)
    "VM Thread" prio=10 tid=0x095dec00 nid=0x141a runnable
    "VM Periodic Task Thread" prio=10 tid=0x93c17400 nid=0x1420 waiting on condition
    JNI global references: 836
    Heap
    def new generation   total 960K, used 152K [0x93f40000, 0x94040000, 0x966a0000)
      eden space 896K,   9% used [0x93f40000, 0x93f56148, 0x94020000)
      from space 64K, 100% used [0x94020000, 0x94030000, 0x94030000)
      to   space 64K,   0% used [0x94030000, 0x94030000, 0x94040000)
    tenured generation   total 4096K, used 1088K [0x966a0000, 0x96aa0000, 0xb3f40000)
       the space 4096K,  26% used [0x966a0000, 0x967b01b0, 0x967b0200, 0x96aa0000)
    compacting perm gen  total 12288K, used 9169K [0xb3f40000, 0xb4b40000, 0xb7f40000)
       the space 12288K,  74% used [0xb3f40000, 0xb4834740, 0xb4834800, 0xb4b40000)
    No shared spaces configured.CLASS1:
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import java.util.concurrent.ExecutionException;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.RepaintManager;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    public class TestClass2 extends JFrame implements ActionListener {
            /** Action Command for <code>searchbtn</code> */
            public static final String SEARCH_BTN_ACTION = "search_btn_action";
             * Constructor.
            public TestClass2() {
                    setSize(650, 350);
                    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    setLocation(screenSize.width / 2 - getSize().width / 2,
                                    screenSize.height / 2 - getSize().height / 2);
                    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowClosing(WindowEvent e) {
                                    exit();
                    JPanel panel = new JPanel();
                    add(panel);
                    setVisible(true);
            @Override
            public void actionPerformed(ActionEvent e) {
                    if (e.getActionCommand().equals(SEARCH_BTN_ACTION)) {
                            JOptionPane.showMessageDialog(this, "Button Pressed");
            public void showWait() {
                    try {
                            WaitDialog.showWaitDialog(this, "Testing...", new SwingWorkerInterface(){
                                    @Override
                                    public Object workToDo() throws Throwable {
                                            Thread.currentThread().sleep(3000);
                                            return null;
                    } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (ExecutionException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
             * Exits the program.
            public void exit(){
                    System.exit(0);
             * Create the GUI and show it. For thread safety, this method should be
             * invoked from the event-dispatching thread.
             * @throws UnsupportedLookAndFeelException
             * @throws IllegalAccessException
             * @throws InstantiationException
             * @throws ClassNotFoundException
             * @throws NullInstanceVariableException
             * @throws SQLException
            private static void createAndShowGUI() {
                    // set look and feel
                    try{
                            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                            // Create instance of the ProductCatalog
                            TestClass2 root = new TestClass2();
                            for(int i = 0; i < 10; i++){
                                    root.showWait();
                    }catch(Exception e){
                            e.printStackTrace();
             * @param args
             *            this program does not use arguments
            public static void main(String[] args) {
                    SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                    createAndShowGUI();
    }CLASS 2:
    import java.awt.Component;
    import java.awt.Frame;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.concurrent.ExecutionException;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.SwingWorker;
    public class WaitDialog extends JDialog {
            private boolean disposed = false;
            private boolean displayed = false;
            private WorkerThread worker = null;
            WaitDialog(Frame parent, String text, SwingWorkerInterface in){
                    super(parent, true);
                    worker = new WorkerThread(in);
                    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowOpened(WindowEvent e) {
                                    worker.execute();
                            @Override
                            public void windowClosing(WindowEvent e) {
                                    disposeWaitDialog();
                    this.setResizable(false);
                    JLabel message = new JLabel();
                    message.setText(text);
                    JProgressBar pb = new JProgressBar();
                    pb.setIndeterminate(true);
                    // set size and location
                    setSize(200, 100);
                    setLocationRelativeTo(parent);
                    JPanel panel = new JPanel();
                    panel.add(message);
                    panel.add(pb);
                    add(panel);
            public void showWaitDialog(){
                    if(displayed == true){
                            return;
                    if(disposed == true){
                            disposed = false;
                            return;
                    disposed = false;
                    displayed = true;
                    setVisible(true);
            public void disposeWaitDialog(){
                    if(disposed == true){
                            return;
                    if(displayed == true){
                            displayed = false;
                            setVisible(false);
                            return;
                    disposed = true;
                    displayed = false;
            public static Object showWaitDialog(Component parent, String text, SwingWorkerInterface in) throws InterruptedException, ExecutionException {
                    WaitDialog waitDialog = null;
                    if (parent == null) {
                            waitDialog = new WaitDialog(JOptionPane.getRootFrame(), text, in);
                    } else {
                            waitDialog = new WaitDialog(JOptionPane.getFrameForComponent(parent), text, in);
                    while(!waitDialog.worker.isDone()){
                            System.out.println("about to show");
                            waitDialog.showWaitDialog();
                            System.out.println("done showing");
                    waitDialog.dispose();
                    return waitDialog.worker.get();
            class WorkerThread extends SwingWorker<Throwable, Void> {
                    private SwingWorkerInterface in = null;
                    WorkerThread(SwingWorkerInterface in){
                            this.in = in;
                    public Throwable doInBackground(){
                                    try {
                                            System.out.println("about to do work");
                                            in.workToDo();
                                            System.out.println("done work no exception");
                                    } catch (Throwable e) {
                                            System.out.println("done work with exception");
                                            return e;
                                    return null;
                    public void done(){
                                    System.out.println("about to dispose");
                                    disposeWaitDialog();
                                    System.out.println("disposed");
    }CLASS 3:
    public interface SwingWorkerInterface {
            public Object workToDo() throws Throwable;
    }

    There's nothing directly wrong with it, but it will
    prevent other threads acquiring the class lock - but
    that may be what you want.True. Although the typical case for code that looks like this would be to use wait--usually the various threads in question require the same lock, so you have to use wait in order for the waiting thread to give it up and allow the other thread to do its work. Hard to say for sure though what he's doing.
    Also, if loading is all that the other thread does, and you're waiting for that thread to die, use join. But then, if that's the case, and you're only waiting for a single other thread, then you might as well just put it all in one thread, as already indicated.

  • Large Memory Usage and Frozen [thread dump attached]

    Hi,
    SQL Developer (Version 2.1.1.64, WinXP Pro, Java 1.6, Oracle 10g R2) always uses at least 550MB of memory, if left open, for more than a day, it invariably goes up to 700-800MB.
    If I close all windows and connections, virtually no memory is reclaimed.
    I clicked + beside a view to see the columns, sqldeveloper froze for a few minutes, below is the thread dump.
    2010-05-21 11:31:58
    Full thread dump Java HotSpot(TM) Client VM (14.2-b01 mixed mode):
    "CONNECTION_ALIVE" prio=6 tid=0x3891c000 nid=0x1d58 waiting for monitor entry [0x3a55f000]
    java.lang.Thread.State: BLOCKED (on object monitor)
    at oracle.jdbc.driver.T4CConnection.doPingDatabase(T4CConnection.java:3398)
    - waiting to lock <0x09ad05f8> (a oracle.jdbc.driver.T4CConnection)
    at oracle.jdbc.driver.PhysicalConnection.pingDatabase(PhysicalConnection.java:7074)
    at oracle.javatools.db.ora.BaseOracleDatabase.isConnectionAlive(BaseOracleDatabase.java:165)
    at oracle.javatools.db.AbstractDatabase$1.run(AbstractDatabase.java:316)
    at java.lang.Thread.run(Thread.java:619)
    "Loading Children" prio=6 tid=0x3891bc00 nid=0x12c4 waiting on condition [0x39d5f000]
    java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x03eab570> (a java.util.concurrent.FutureTask$Sync)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:747)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:905)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1217)
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:218)
    at java.util.concurrent.FutureTask.get(FutureTask.java:83)
    at oracle.dbtools.raptor.backgroundTask.RaptorTaskManager$IdeTaskTracker.run(RaptorTaskManager.java:532)
    at java.lang.Thread.run(Thread.java:619)
    "pool-2-thread-57" prio=6 tid=0x3891b400 nid=0x2094 waiting on condition [0x35b5f000]
    java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x09b819f0> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:198)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireNanos(AbstractQueuedSynchronizer.java:841)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireNanos(AbstractQueuedSynchronizer.java:1160)
    at java.util.concurrent.locks.ReentrantLock.tryLock(ReentrantLock.java:416)
    at oracle.dbtools.raptor.utils.Connections.lock(Connections.java:1334)
    at oracle.dbtools.raptor.utils.Connections.lock(Connections.java:1319)
    at oracle.dbtools.raptor.utils.Connections.lock(Connections.java:1306)
    at oracle.dbtools.raptor.navigator.xml.AbstractItemInstance.lockConnection(AbstractItemInstance.java:52)
    at oracle.dbtools.raptor.navigator.xml.XmlNodeInstance.listChildren(XmlNodeInstance.java:55)
    at oracle.dbtools.raptor.navigator.ObjectNodeFilter$ObjectNodeFilterLoadTask.doWorkImpl(ObjectNodeFilter.java:78)
    at oracle.dbtools.raptor.navigator.DeferredLoadingFilter$FilterLoadTask.doWork(DeferredLoadingFilter.java:124)
    at oracle.dbtools.raptor.navigator.DeferredLoadingFilter$FilterLoadTask.doWork(DeferredLoadingFilter.java:113)
    at oracle.dbtools.raptor.backgroundTask.RaptorTask.call(RaptorTask.java:193)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at oracle.dbtools.raptor.backgroundTask.RaptorTaskManager$RaptorFutureTask.run(RaptorTaskManager.java:492)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
    "pool-2-thread-55" prio=6 tid=0x38d68400 nid=0xd74 runnable [0x3a15f000]
    java.lang.Thread.State: RUNNABLE
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at oracle.net.ns.Packet.receive(Packet.java:239)
    at oracle.net.ns.DataPacket.receive(DataPacket.java:92)
    at oracle.net.ns.NetInputStream.getNextPacket(NetInputStream.java:172)
    at oracle.net.ns.NetInputStream.read(NetInputStream.java:117)
    at oracle.net.ns.NetInputStream.read(NetInputStream.java:92)
    at oracle.net.ns.NetInputStream.read(NetInputStream.java:77)
    at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1023)
    at oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:999)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:584)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:785)
    at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:860)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1186)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3381)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3425)
    - locked <0x09ad05f8> (a oracle.jdbc.driver.T4CConnection)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1490)
    at oracle.dbtools.raptor.controls.grid.ResultSetTableModel.openResultSet(ResultSetTableModel.java:412)
    at oracle.dbtools.raptor.controls.grid.ResultSetTableModel.fetchNext(ResultSetTableModel.java:169)
    at oracle.dbtools.raptor.controls.grid.ResultSetTableModel$4.doWork(ResultSetTableModel.java:556)
    at oracle.dbtools.raptor.controls.grid.ResultSetTableModel$4.doWork(ResultSetTableModel.java:540)
    at oracle.dbtools.raptor.backgroundTask.RaptorTask.call(RaptorTask.java:193)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at oracle.dbtools.raptor.backgroundTask.RaptorTaskManager$RaptorFutureTask.run(RaptorTaskManager.java:492)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
    "AWT-EventQueue-0" prio=6 tid=0x354fac00 nid=0x18d4 waiting for monitor entry [0x3a45f000]
    java.lang.Thread.State: BLOCKED (on object monitor)
    at oracle.jdbc.driver.PhysicalConnection.getMetaData(PhysicalConnection.java:3891)
    - waiting to lock <0x09ad05f8> (a oracle.jdbc.driver.T4CConnection)
    at oracle.dbtools.raptor.plscope.Query.getToolTipText(Query.java:58)
    at oracle.dbtools.raptor.phighlight.TooltipPlugin$1.getToolTipText(TooltipPlugin.java:29)
    at oracle.ide.ceditor.CodeEditor.getToolTipText(CodeEditor.java:1734)
    - locked <0x17245f98> (a java.util.ArrayList)
    at oracle.javatools.editor.BasicEditorPane.getToolTipText(BasicEditorPane.java:1530)
    at javax.swing.ToolTipManager$insideTimerAction.actionPerformed(ToolTipManager.java:658)
    at javax.swing.Timer.fireActionPerformed(Timer.java:271)
    at javax.swing.Timer$DoPostEvent.run(Timer.java:201)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    "Background Parser" prio=6 tid=0x38a43400 nid=0x23c4 waiting on condition [0x39c5f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at oracle.dbtools.raptor.plsql.BackgroundParser$1.construct(BackgroundParser.java:112)
    at oracle.dbtools.raptor.utils.NamedSwingWorker$2.run(NamedSwingWorker.java:115)
    at java.lang.Thread.run(Thread.java:619)
    "SwingWorker-pool-5-thread-1142" prio=6 tid=0x38868800 nid=0x1a7c waiting on condition [0x3820f000]
    java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x0e77bc10> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:1925)
    at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:358)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
    "Background Parser" prio=6 tid=0x38a76c00 nid=0x1d18 waiting on condition [0x3a35f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at oracle.dbtools.raptor.plsql.BackgroundParser$1.construct(BackgroundParser.java:112)
    at oracle.dbtools.raptor.utils.NamedSwingWorker$2.run(NamedSwingWorker.java:115)
    at java.lang.Thread.run(Thread.java:619)
    "Background Parser" prio=6 tid=0x387e2800 nid=0xd00 waiting on condition [0x3a25f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at oracle.dbtools.raptor.plsql.BackgroundParser$1.construct(BackgroundParser.java:112)
    at oracle.dbtools.raptor.utils.NamedSwingWorker$2.run(NamedSwingWorker.java:115)
    at java.lang.Thread.run(Thread.java:619)
    "Background Parser" prio=6 tid=0x38752000 nid=0x2794 waiting on condition [0x39e5f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at oracle.dbtools.raptor.plsql.BackgroundParser$1.construct(BackgroundParser.java:112)
    at oracle.dbtools.raptor.utils.NamedSwingWorker$2.run(NamedSwingWorker.java:115)
    at java.lang.Thread.run(Thread.java:619)
    "Swing-Shell" daemon prio=6 tid=0x367f0000 nid=0xd7c waiting on condition [0x3a85f000]
    java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x1069d0d8> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:1925)
    at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:358)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at sun.awt.shell.Win32ShellFolderManager2$ComInvoker$3.run(Win32ShellFolderManager2.java:458)
    at java.lang.Thread.run(Thread.java:619)
    "Persistence Auto Flusher" daemon prio=6 tid=0x388a5c00 nid=0x1950 in Object.wait() [0x37e0f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at java.util.TimerThread.mainLoop(Timer.java:483)
    - locked <0x0e892d48> (a java.util.TaskQueue)
    at java.util.TimerThread.run(Timer.java:462)
    "Thread-76" prio=6 tid=0x387aec00 nid=0x259c runnable [0x00000000]
    java.lang.Thread.State: RUNNABLE
    "WeakDataReference polling" prio=2 tid=0x38752800 nid=0xe94 in Object.wait() [0x3a05f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118)
    - locked <0x0b6ba260> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
    at oracle.ide.util.WeakDataReference$Cleaner.run(WeakDataReference.java:88)
    at java.lang.Thread.run(Thread.java:619)
    "Image Animator 3" daemon prio=4 tid=0x3861b400 nid=0x2330 waiting on condition [0x3978f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at sun.awt.image.GifFrame.dispose(GifImageDecoder.java:653)
    at sun.awt.image.GifImageDecoder.produceImage(GifImageDecoder.java:230)
    at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:246)
    at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
    at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
    "Background Parser" prio=6 tid=0x38348800 nid=0x978 waiting on condition [0x3988f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at oracle.dbtools.raptor.plsql.BackgroundParser$1.construct(BackgroundParser.java:112)
    at oracle.dbtools.raptor.utils.NamedSwingWorker$2.run(NamedSwingWorker.java:115)
    at java.lang.Thread.run(Thread.java:619)
    "TextBufferScavenger" prio=6 tid=0x38324800 nid=0x1af0 in Object.wait() [0x3968f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118)
    - locked <0x09bb9158> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
    at oracle.ide.model.TextNode$FacadeBufferReference$PollingThread.run(TextNode.java:1949)
    "pool-4-thread-1" prio=6 tid=0x36960400 nid=0x1a84 waiting on condition [0x35a5f000]
    java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x08150a78> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:198)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:1963)
    at java.util.concurrent.DelayQueue.take(DelayQueue.java:164)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:583)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:576)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
    "IconOverlayTracker Timer" prio=6 tid=0x38520c00 nid=0x1b48 in Object.wait() [0x3950f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at java.util.TimerThread.mainLoop(Timer.java:483)
    - locked <0x0795f290> (a java.util.TaskQueue)
    at java.util.TimerThread.run(Timer.java:462)
    "Timer queue for AWT thread" daemon prio=6 tid=0x369b4000 nid=0x1f20 in Object.wait() [0x3940f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x077e1358> (a java.lang.Object)
    at java.lang.Object.wait(Object.java:485)
    at ice.util.awt.TimedAWTExecutor.nextElem(TimedAWTExecutor.java:108)
    - locked <0x077e1358> (a java.lang.Object)
    at ice.util.awt.TimedAWTExecutor.runScheduler(TimedAWTExecutor.java:130)
    at ice.util.awt.TimedAWTExecutor$1.run(TimedAWTExecutor.java:19)
    "WaitCursor-Timer" prio=6 tid=0x367c3c00 nid=0x1010 in Object.wait() [0x37b0f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at java.util.TimerThread.mainLoop(Timer.java:483)
    - locked <0x077e1400> (a java.util.TaskQueue)
    at java.util.TimerThread.run(Timer.java:462)
    "Native Directory Watcher" prio=2 tid=0x368d4000 nid=0x2334 runnable [0x3830f000]
    java.lang.Thread.State: RUNNABLE
    at oracle.ide.natives.NativeHandler.enterWatcherThread(Native Method)
    at oracle.ide.natives.NativeHandler$2.run(NativeHandler.java:252)
    at java.lang.Thread.run(Thread.java:619)
    "BaseTreeExplorer.NodeOpeningExecutor" prio=6 tid=0x3684b000 nid=0x8b0 waiting on condition [0x3810f000]
    java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x06950af0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:1925)
    at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:358)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
    "Scheduler" daemon prio=6 tid=0x36846400 nid=0x14bc in Object.wait() [0x37f0f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at oracle.dbtools.raptor.backgroundTask.TaskLinkedList.takeNextTask(TaskLinkedList.java:47)
    - locked <0x06950c70> (a oracle.dbtools.raptor.backgroundTask.TaskLinkedList)
    at oracle.dbtools.raptor.backgroundTask.RaptorTaskManager$SchedulerThread.run(RaptorTaskManager.java:422)
    "TimerQueue" daemon prio=6 tid=0x36832800 nid=0x88c in Object.wait() [0x37d0f000]
    java.lang.Thread.State: TIMED_WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at javax.swing.TimerQueue.postExpiredTimers(TimerQueue.java:218)
    - locked <0x06950da8> (a javax.swing.TimerQueue)
    at javax.swing.TimerQueue.run(TimerQueue.java:234)
    - locked <0x06950da8> (a javax.swing.TimerQueue)
    at java.lang.Thread.run(Thread.java:619)
    "ChangeSetService" prio=2 tid=0x367fd400 nid=0x2754 in Object.wait() [0x37c0f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x06892cc0> (a oracle.jdevimpl.vcs.changeset.ChangeSetService)
    at java.lang.Object.wait(Object.java:485)
    at oracle.jdevimpl.vcs.changeset.ChangeSetService.awaitEvents(ChangeSetService.java:178)
    - locked <0x06892cc0> (a oracle.jdevimpl.vcs.changeset.ChangeSetService)
    at oracle.jdevimpl.vcs.changeset.ChangeSetService.eventLoop(ChangeSetService.java:199)
    at oracle.jdevimpl.vcs.changeset.ChangeSetService.access$200(ChangeSetService.java:56)
    at oracle.jdevimpl.vcs.changeset.ChangeSetService$2.run(ChangeSetService.java:138)
    at java.lang.Thread.run(Thread.java:619)
    "TimedCache-Timer" daemon prio=6 tid=0x35d52c00 nid=0x2448 in Object.wait() [0x3624f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at java.util.TimerThread.mainLoop(Timer.java:483)
    - locked <0x062ab118> (a java.util.TaskQueue)
    at java.util.TimerThread.run(Timer.java:462)
    "JarIndex Timer" daemon prio=6 tid=0x35556400 nid=0x2488 in Object.wait() [0x35d4f000]
    java.lang.Thread.State: TIMED_WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.util.TimerThread.mainLoop(Timer.java:509)
    - locked <0x062206e0> (a java.util.TaskQueue)
    at java.util.TimerThread.run(Timer.java:462)
    "AWT-Windows" daemon prio=6 tid=0x354dd000 nid=0x1d0c runnable [0x3595f000]
    java.lang.Thread.State: RUNNABLE
    at sun.awt.windows.WToolkit.eventLoop(Native Method)
    at sun.awt.windows.WToolkit.run(WToolkit.java:291)
    at java.lang.Thread.run(Thread.java:619)
    "AWT-Shutdown" prio=6 tid=0x354a1800 nid=0x268c in Object.wait() [0x3585f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at sun.awt.AWTAutoShutdown.run(AWTAutoShutdown.java:259)
    - locked <0x062208d8> (a java.lang.Object)
    at java.lang.Thread.run(Thread.java:619)
    "Java2D Disposer" daemon prio=10 tid=0x354b7400 nid=0x5f4 in Object.wait() [0x3575f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118)
    - locked <0x06220968> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
    at sun.java2d.Disposer.run(Disposer.java:125)
    at java.lang.Thread.run(Thread.java:619)
    "Low Memory Detector" daemon prio=6 tid=0x00ee1000 nid=0x2664 runnable [0x00000000]
    java.lang.Thread.State: RUNNABLE
    "CompilerThread0" daemon prio=10 tid=0x00edc000 nid=0x1f6c waiting on condition [0x00000000]
    java.lang.Thread.State: RUNNABLE
    "Attach Listener" daemon prio=10 tid=0x00eda800 nid=0x206c runnable [0x00000000]
    java.lang.Thread.State: RUNNABLE
    "Signal Dispatcher" daemon prio=10 tid=0x00ed9400 nid=0xf64 waiting on condition [0x00000000]
    java.lang.Thread.State: RUNNABLE
    "Finalizer" daemon prio=8 tid=0x00ec6c00 nid=0x2348 in Object.wait() [0x34e7f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118)
    - locked <0x061b0298> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159)
    "Reference Handler" daemon prio=10 tid=0x00ec5800 nid=0x2484 in Object.wait() [0x34d7f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:116)
    - locked <0x061b0320> (a java.lang.ref.Reference$Lock)
    "main" prio=6 tid=0x009f8000 nid=0x19e0 waiting on condition [0x00000000]
    java.lang.Thread.State: RUNNABLE
    "VM Thread" prio=10 tid=0x00ec1800 nid=0x22e0 runnable
    "VM Periodic Task Thread" prio=10 tid=0x00eec000 nid=0x2604 waiting on condition
    JNI global references: 5312
    Heap
    def new generation total 45376K, used 28499K [0x03080000, 0x061b0000, 0x061b0000)
    eden space 40384K, 67% used [0x03080000, 0x04af44c0, 0x057f0000)
    from space 4992K, 28% used [0x05cd0000, 0x05e30850, 0x061b0000)
    to space 4992K, 0% used [0x057f0000, 0x057f0000, 0x05cd0000)
    tenured generation total 604992K, used 364537K [0x061b0000, 0x2b080000, 0x2b080000)
    the space 604992K, 60% used [0x061b0000, 0x1c5ae548, 0x1c5ae600, 0x2b080000)
    compacting perm gen total 57344K, used 57260K [0x2b080000, 0x2e880000, 0x33080000)
    the space 57344K, 99% used [0x2b080000, 0x2e86b348, 0x2e86b400, 0x2e880000)
    No shared spaces configured.
    Edited by: mdaly on May 21, 2010 11:42 AM

    The cause of hang could be figured out from the thread dump.
    I have fixed that in development code. It was happening from PL/SQL editor trying to create tooltip which locked up the connection.
    I am not sure what would lead to memory bloat even if the tool is not in use. There could be memory leak from some component. I am investigating that.
    Suggest you to keep ObjectViewers, reports & PL/SQL editor closed when not in use.
    Have Sql Array Fetch Size preference to 50 if it's higher.
    Do not have auto-refresh for Report editor.
    Keep Sql History, Find Db Object, Snippets collapsed.
    See if that helps.
    -Raghu

  • Is there a way to figure out what the current thread is?

    I've got the following snippet of code:
    // create a new thread. If the current thread is not this new thread, return
    Thread CountDownThread = new Thread("CountDownThread");
    CountDownThread.start();
    if (/*CURRENT THREAD*/.getName() != CountDownThread.getName()) {
         System.out.println ("I'm not CountDownThread. I'm leaving.");
         return;
    // current thread should be new thread. Therefore start the countdown
    CurrTime = InitTime;
    while(CurrTime.charAt(0) != '-') {      // go until current time is negative
         CurrTime = C.countDown();       // returns the current time based on the difference between the initial and elapsed time
         setText(CurrTime);                   // display current time in JLabel
    C.reset();
    setText(C.getCurrTime());What I'm trying to do is get a clock (C) to count down and display the time remaining in a JLabel (this snippet is taken from a method within that very JLabel which I'm extending from javax.swing.JLabel). While it's counting down, I'd like for the program to go off and do other things. Therefore, I'm trying to create a new thread that carries out the task of counting down while the original/main thread moves on to do other things.
    Please have a look at the above code and tell me if I'm on the right track. The one thing I don't know how to do is figure out how to tell which thread the current thread is. I'm assuming that both the new thread and original/main one will execute the if statement, the new one after it returns from start() (which I haven't defined). The original/main one will detect that it is not the new thread and return, whereas the new thread will and go on to the while loop. In the while loop, it will count down the clock until it reaches 0, after which point it will reset it and die.
    If I'm on the right track, all I need to know is how to detect which thread is currently executing. If I'm not on the right track, what would be the best way to do this?

    What? No! No Thread terminates on the return of start(). Those two events are unrelated!Uh... I think you misunderstood what I said.
    I didn't say that CountDownThread terminates upon returning from start() (which is what it sounds like you interpreted from me); I said that the thread that CountDownThread creates terminates once CountDownThread returns from start() (i.e. like any other local variable/object). This, of course, assumes that CountDownThread has a Runnable object on which to call its run() method (am I right?), in which case my code above doesn't create a new thread at all (i.e. CountDownThread.start() is executed within the main/original thread) - am I right?
    No, run() doesn't call start()! That would be stupid.Again, you misunderstood. I shouldn't need to explain this one. A simple reference to an ordinary dictionary on the words 'former' and 'latter' should suffice :)
    Anyway, all joking aside, I have now improved my code and it works! Here's what it looks like:
    ClockJLabel.java
    package MazeMania.clock;
    public class ClockJLabel extends javax.swing.JLabel {
    private Clock C;
    private ClockJLabelsRunnable CJLR;
    public ClockJLabel() {
      C = new Clock();
      CJLR = new ClockJLabelsRunnable();
      setText(C.getCurrTime()); // should be 00:00:00:00
      setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
      // need to figure out how to set the size so that it sticks
      setForeground(new java.awt.Color(255, 0, 0));
      setBackground(new java.awt.Color(0, 0, 0));
      setOpaque(true);
    // starts the clock counting up indefinitely from 0
    public void start() {
      (new Thread(new Runnable() {
        public void run() {
         while(true) setText(C.getElapsedTime());
       })).start();
      //System.out.println("Started clock...");
    // starts the clock counting down from an initial time and runs this count down in a separate thread
    public void countDown(String InitTime) {
      // initialize the clock
      try {C.initClock(InitTime);}
      catch(java.text.ParseException PE) {
       System.out.println(PE.getMessage());
      // initialize JLabel's display
      setText(C.getCurrTime());
      // prepare Runnable and give it to new Thread. New Thread starts count down.
      CJLR.task = CJLR.COUNTDOWN;
      CJLR.CJL = this;
      Thread CountDownThread = new Thread(CJLR);
      CountDownThread.start();
    public Clock getClock() {
      return C;
    }ClockJLabelsRunnable
    package MazeMania.clock;
    import java.lang.Runnable;
    class ClockJLabelsRunnable implements Runnable {
    public static int COUNTDOWN = 1;
    public static int COUNTUP = 2;
    // NOTE: this Runnable doesn't test for the proper setting of these variables
    public int task = 0;
    public ClockJLabel CJL = null;
    public void run() {
      Clock C = CJL.getClock();
      while(C.countDown().charAt(0) != '-') {CJL.setText(C.getCurrTime());}
      C.reset();
      CJL.setText(C.getCurrTime());

  • Why do threads run one at a time?

    [Newbie] Couldn't get help in another forum, so here goes. Tried this in Netbeans 3.5 then at home later in BlueJ, same thing. Thanks in advance!
    I have written a small application to play with threads. I create 3 instances of a class and shoot each one off in a thread, but they all seem to run one at a time, not at the same time. I have posted the code below. The output I expect is something like this:
    0T1
    0T2
    0T3
    1T1
    1T2
    1T3
    2T1
    2T2
    2T3
    498T1
    498T2
    498T3
    499T1
    499T2
    499T3
    500T1
    500T2
    500T3
    The T1 means threadstart1 wrote that line, the T3, means threadstart3 wrote the line, etc. I would expect to see these slightly out of order, too, knowing that the threads will process what they can, when they can. Instead, I see this:
    0T1
    1T1
    2T1
    500T1
    0T2
    1T2
    2T2
    500T2
    0T3
    1T3
    2T3
    500T3
    It's in perfect numeric order, each completing before the next starts. What am I doing wrong?
    //-------------dostuff.java
    package delme2;
    public class dostuff implements Runnable {
    private String mtext;
    public dostuff(String atext) {
    mtext = atext;
    public void run() {
    int j;
    String s;
    //display 500 numbers
    for (j=0; j<500; j++) {
    //build the string
    s = String.valueOf(j) + mtext;
    //show the string
    System.out.println(s);
    //wait a bit before doing this again.
    try {
    Thread.sleep(10);
    } catch (InterruptedException e) {
    //--------------- delme2.java
    package delme2;
    public class delme2 {
    public delme2() {
    System.out.println("Thread demo:");
    Runnable threadstart1 = new dostuff("T1");
    Runnable threadstart2 = new dostuff("T2");
    Runnable threadstart3 = new dostuff("T3");
    Thread t1 = new Thread( threadstart1 );
    Thread t2 = new Thread( threadstart2 );
    Thread t3 = new Thread( threadstart3 );
    t1.run();
    t2.run();
    t3.run();
    public static void main(String[] args) {
    delme2 mydelme2 = new delme2();
    }

    Okay, I'll play along. Having written a task scheduler in C (under tutorial, I admit), I think I qualify. A task scheduler has three jobs at all times.
    1) Execute the code at hand.
    2) Figure out when to stop executing the code at hand.
    3) When stopped, figure out what code to execute next.
    When executing a piece of code, there are different paradigms for determining when to stop and move on. Ideally, a cooperative multitasking system would have threads that relinquish timeslices or have some other method sprinkled throughout their code that indicates to the task scheduler that it's okay to move on to another piece of code. In my experience, that indicator is a Thread.Sleep() or equiavalent. when the thread.sleep() is encountered. The task scheduler has nothing to do for a whopping 10 MS. It could even take 15 or 20 ms if the next process in line takes that long. So what is it doing for 10 ms? It's not executing those other threads, which should be queued for their turn on step #3 as soon as I fire them off with a .run().
    Now, I hope you can see that I've given this some thought and read about it, but I'm missing something. I can get a very similar project to work as I expect it to in .NET and in Delphi. The Java environment has something different about it that I haven't figured out. Here's the c# code that does EXACTLY what I want it to. All threads run at a same time, and I get 0,0,0,1,1,1,2,2,2,3,3,3,4,4,4, etc.. See the similarities?
              private void button1_Click(object sender, System.EventArgs e)
                   lst.Items.Clear();
                   ThreadStart start1 = new ThreadStart(runner);
                   ThreadStart start2 = new ThreadStart(runner);
                   ThreadStart start3 = new ThreadStart(runner);
                   Thread t1 = new Thread(start1);
                   Thread t2 = new Thread(start2);
                   Thread t3 = new Thread(start3);
                   t1.Start();
                   t2.Start();
                   t3.Start();
              private void runner()
                   string s;
                   for (int j=0; j<500; j++)
                        s = j.ToString();
                        lst.Items.Add(s);
                        Thread.Sleep(10);
              }

Maybe you are looking for

  • How do I Load a clob from an XML field in an XMLTYPE using XMLTABLE ?

    I am trying to load data into a CLOB from a XML field using XMLTABLE. I have a SUMMARY xml field with over 100 K of data (potentialy) and I can load all the other datatype fields to columns but can not load the xml fields over 4000 characters. exampl

  • Can't View IPod Library from ITunes

    I have updated to ITunes 7.0 and updated my IPod, but for some reason I am not able to view the library in my IPod. The computer recognizes the IPod and will play the songs on it, I just can't view the songs to select a specific song or search throug

  • I keep getting an internal server error when I try to load pages in live preview in edge code...

    I keep getting this message every time I try to laod a page using live preview in Edge Code with Google chrome... "The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server adminis

  • When mirroring - can I turn off the monitor on my Mac...?

    I just set up my MacBook Pro with my AppleTV and everything is working nicely. However, It would be even better if I could get my computer monitor to turn off while I'm viewing on my TV. Is this possible?

  • Monitor calibration for 27 in imac

    I need to know how to calibrate my monitor so that I know what my photographs are going to look like before they get printed.  Either that or would it be better to buy a third party calibrator, like X-rite?