The thread object

Hello,
Is a thread only represented by a single Thread object?
In other words, when you invoke the Thread.currentThread() method does this method return a reference to the same Thread object that was used to create the thread?
One more thing, is the Thread object representing a thread ever garbage collected if there are no references to the object?
Thanks

Given the fact that the class Thread represents a thread in the JVM, I would conjecture "yes".
If the thread is still running, any Thread.currentThread() invocation can yield a reference to it, so it is not unreachable and will not be garbage collected.
Whether a thread will be garbage collected post-mortem, that is, after it exited from its run method, could depend on whether a reference if still held internally by the JVM. There is some internal handling of the threads (let us also think about ShutdownHooks and the like), which might belong to the implementation details of the given JVM.
I remember some bug with created but not started threads being not garbage collected. They got into some queue of the threads-to-be-started-in-the-future which hampered their being gc'ed.
while (true) {
    Thread t =new Thread (new MyRunnable());
}

Similar Messages

  • Two Threads Sharing the Same Object

    I am learning Java multithreading recently and I really hit the wall when I came to synchronizing data using the synchronized keyword. According to the explanation, synchronized will only work when 2 or more threads are accessing the same object. If there are accessing 2 different objects, they can run the synchronized method in parallel.
    My question now is how to make sure for synchronized method to work, I am actually working with the same and only one object??
    Imagine this:
    Two person with the same account number are trying to access the very ONE account at the same time.
    I suppose the logic will be:
    Two different socket objects will be created. When it comes to the login or authentication class or method, how can I make sure in term of object that the login/authentication class or method will return them only ONE object (because they share the same account), so that they will be qualified for using the synchronized method further down the road?
    Thanks in advance!

    Actually your understanding is wrong. Consider:
    public class MyClass {
      private int someInt;
      private float someFloat;
      private synchronized void someMethod(final int value) {
        if (value > 2000) someInt = 2000;
      private synchronized void someOtherMethod(final float value) {
        if (value > 2.0) someFloat = 1.999f;
    }YOu might think that two different threads can enter this code, one can enter in someOtherMethod() while one is in someMethod(). That is wrong. The fact is that synchronization works by obtaining synchronization locks on a target object. In this case by putting it on the method declaration you are asking for the lock on the 'this' object. This means that only one of these methods may enter at a time. This code would be better written like so ...
    public class MyClass {
      private int someInt;
      private float someFloat;
      private void someMethod(final int value) {�
        synchronized(someInt) {
          if (value > 2000) someInt = 2000;
      private void someOtherMethod(final float value) {
        synchronized(someFloat) {
          if (value > 2.0) someFloat = 1.999f;
    }In this manner you are only locking on the pertinent objects to the method and not on 'this'. This means that both methods can be entered simultaneously by two different threads. However watch out for one little problem.
    public class MyClass {
      private int someInt;
      private float someFloat;
      private void someMethod(final int value) {�
        synchronized(someInt) {
          if (value > 2000) {
            someInt = 2000;
            synchronized (someFloat) {
              someFloat = 0.0f;
      private void someOtherMethod(final float value) {
        synchronized(someFloat) {
          if (value > 2.0) {
            someFloat = 1.99999f;
            synchronized (someInt) {
              someInt = 0;
    }In this case you can have a deadlock. If two threads enter one of these methods at the same time one would be waiting on the lock for someInt and the other on the lock for someFloat. Neither would proceed. The solution to the problem is simple. Acquire all locks in alphabetical order before you use the first.
    public class MyClass {
      private int someInt;
      private float someFloat;
      private void someMethod(final int value) {�
        synchronized (someFloat) {
          synchronized(someInt) {
            if (value > 2000) {
              someInt = 2000;
              someFloat = 0.0f;
      private void someOtherMethod(final float value) {
        synchronized(someFloat) {
          if (value > 2.0) {
            someFloat = 1.99999f;
            synchronized (someInt) {
              someInt = 0;
    }In this manner one thread will block waiting on someFloat and there can be no deadlock.

  • "there were not enough threads in the threadpool object to complete the operation" exception

    Post Author: crystalmatrix
    CA Forum: .NET
    I have a WinForm application using a Crystal Report Viewer control that in turn connects to a CR web service to display report. The client side application runs on WinXP SP1 with .Net framework 1.1, and the server is Win2k with ASP.Net 1.1. I am using CR XI out of the box.
    Users would periodically get "there were not enough threads in the threadpool object to complete the operation." exception when trying to launch the report viewer connected to the web service. The web service is a standard example implementation derived from CrystalDecisions.Web.Services.ReportServiceBase class. The problem usually happens when the user tries to open multiple report viewer forms, but once they get the error, it would continue to happen even after the user shuts down all viewer forms and then tries to launch a new one.
    There are some posts on the web regarding multiple asynchronous HttpWebRequest draining threadpool when running simultaneously and each one taking a long time to complete. However, our reports all run pretty quickly and results are usually returned before the next report starts to run. So my question is: does Crystal Report Viewer control has a problem with web service in that it may hold the HttpWebRequest thread even after the report is returned, or any other problem that may prevents the asynchronous thread being released back to the Threadpool? Anyone has experienced similar problems and has a workaround?
    Any advice is appreciated.

    Find your serial number quickly

  • Will subsequent calls to an object running in a thread run in the thread?

    Hi,
    If I start a thread with an empty run method and then make a call to the object that I started in the thread, will the method call run in the other thread? For example:
    class ThreadClass implements Runnable {
        public void someMethod() {
        public void run() {
    class ThreadCaller {
        private ThreadClass threadClass;
        public ThreadCaller() {
            threadClass = new ThreadClass();
            Thread thread = new Thread(threadClass);
            thread.start();
        public blah() {
            threadClass.someMethod();
    }Will the method call in blah() run in the same thread as ThreadCaller, or will it run in the thread that was started in ThreadCaller's constructor?
    Thanks,
    Dan

    Djaunl wrote:
    vanilla_lorax wrote:
    Djaunl wrote:
    Is there a way to keep the thread alive until the object that started the thread is terminated,Objects don't get terminated. What do you mean?I want the thread to stay alive indefinitely until I arbitrarily terminate it makes more sense. The thread will stay alive until its run method completes. The canonical approaches are
    public void run() {
      while (!Thread.interrupted()) { // NOT isInterrupted()
        // do stuff
        // if you need to catch InterruptedException, do this:
        try {
        catch (InterruptedException exc) {
          Thread.currentThread().interrupt();
    }And then from another thread, call theAboveThread.interrupt() when it's time to stop. Read the docs in interrupt(), interrupted(), the interrupt flag, etc.
    OR
    while (!done()) {
      // do stuff
    }and then another thread calls setDone(true) or somesuch when it's time to stop. Note that all access to done--both get and set--must be synchronized, or done must be declared volatile. Also note that you may still have to handle interrupts, so you may have some repeated code with this approach--testing both done() and interrupted().
    Let me give the end-goal of this.
    Currently, I have a "main" thread which the user can input commands into, and another thread which occasionally runs in the background. When I want something to run in the background, I just create a new thread. However, I figured it'd be more efficient to have one thread running in the background to do something as opposed to spawning hundreds of new threads to do the same task over and over. If the task happens VERY frequently and what it does is VERY small and quick, then the overhead of thread creation may make this a valid approach. Otherwise, don't overcomplicate it. Since you're new to threads, first get it working where you spawn one thread for each background task. Then move on to thread pooling. Look into ThreadPoolExecutor and related classes.
    http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html

  • Accessing object of the main class from the thread

    Hi, I'm having problem accessing object of the main class from the thread. I have only one Thread and I'm calling log.append() from the Thread. Object log is defined and inicialized in the main class like this:
    public Text log;  // Text is SWT component
    log = new Text(...);Here is a Thread code:
    ...while((line = br.readLine())!=null) {
         try {
              log.append(line + "\r\n");
         } catch (SWTException swte) {
              ErrorMsg("SWT error: "+swte.getMessage());
    }Error is: org.eclipse.swt.SWTException: Invalid thread access
    When I replace log.append(...) with System.out.println(..) it works just fine, so my question is do the log.append(..) the right way.

    This is NOT a Java problem but a SWT specific issue.
    It is listed on the SWT FAQ page http://www.eclipse.org/swt/faq.php#uithread
    For more help with this you need to ask your question on a SWT specific forum, there is not a thing in these forums. This advice isn't just about SWT by the way but for all specific API exceptions/problems. You should take those questions to the forum or mailing list for that API. This forum is for general problems and exceptions arising from using the "core" Java libraries.

  • Make sure 2 threads share the same object

    I have been thinking about this for quite some time. However, I really couldn't figure it out due lack of experience and knowledge.
    I just needed to know how can I make sure that 2 or more threads (after certain checkings that they should share a same common object) will really share the same object.
    For example (to UlrikaJ if you are reading this):
    How can I achieve the following?? Thanks!
    "When James and Ada separately want to access their shared account,two transactions are started that accesses the object associated with that account number."

    Thanks for the answer. You are welcome :-)
    public class Account
       public Account getAccount(String userInput)
         // Some processes to verify the userInput go here.
         return account;
    }//End of Account class
    public UserThread implements Runnable
       private String name;
       private Semaphore s;
       private Account userAccount; //Reference for the Account class
       public UserThread(String name, Semaphore s)
          this.name = name;
          this.s = s;
       }//End of constructor
       public void run()
          for(;;)
              getUserInput(); //Ofcourse the implementation will depend on what you are doing
              s.lock(); //obtain a lock on Semaphore object
              //Entering critical section of the code
              this.userAccount = accountObject.getAccount(userInput);
              //End of critical section of the code.
              s.signal(); //Release the lock so that other thread
              //can access the getAccount() method...irrespective of the
              //variable or the object being used or referred to.
          }//End of for() loop
       }//End of run() method
    } //End of UserThread class
    public class AccountApplication
       public static void main(String args[])
          Semaphore sem = new Semaphore(0);
          //Always initialize the Semaphore with 0 when you create it.
          UserThread user1 = new UserThread("User Number 1",sem);
          UserThread user2 = new UserThread("User Number 2",sem);
          //All threads share the same Semaphore object
          Thread userThread1 = new Thread(user1);
          Thread userThread2 = new Thread(user2);
          userThread1.start();
          userThread2.start();
       }//End of main() method
    }//End of classWell, I have given the outline of the code. I have not compiled or run the program so it might have errors in its syntax.
    Obviously, you will definitely have to change it to suit your requirements. I have just shown you how to protect yur codes' critical section.
    Hope this clears your doubts.
    Vijay :-)

  • Error while activating the info object.

    Hi,
    While activating one of the info objects, i am getting the following error message:
    Characteristic 0BP_GRP: Cannot switch off InfoProvider property
    Message no. R7B289
    Diagnosis
    The characteristic receives master data from other objects (for example, transformations or update rules). Therefore it is necessary to select the characteristic as an InfoProvider.
    Procedure
    If you want to deselect the Characteristic Is InfoProvider indicator, delete the corresponding objects in the data flow.
    Thanks and Regards
    Niren.

    Hi Niren,
    Check the below thread..
    Howto Remove 0Employee Char from my InfoArea
    Hope it helps..
    Regards,
    Ramki.

  • Problem with IBM JVM or the Thread

    Hi All,
    I have a class which implements Runnable. The purpose of the program is to read a file and count the number of lines present in that.
    I am using the IBM JVM. The logic runs like this..
    For each 2048 bytes read , it spawns a new thread with this object and each such new thread counts the no. of newline chars present. Once the thread is finished with its 2048 bytes it upddates an instance variable , count, to that value , updates the boolean done flag to "true" and stops. Once the whole file is read(thereby creating filesize/2048 threads ) , it keeps waiting for the threads to finish and then adds all the counts.
    Now the problem is that for some reason these threads seem to hang. There are no static vars present.
    Pls help.
    Tx

    Help yourself first.
    If this is "Windows", try typing Ctrl-Break in your window (Type Ctrl-\ if you're on Windows). This will produce a thread dump with all of your threads.
    See which ones are running, and what they're doing.
    Did you remember to either make your threads daemons (setDaemon(true)), or explicitly exit the run() method of the threads?

  • How do I use multiple classes to access the same object?

    This should be staightforward. I have and object and I have multiple GUIs which operate on the same object. Do all the classes creating the GUIs need to be inner classes of the data class? I hope this question makes sense.
    Thanks,
    Mike

    public final class SingletonClass {
    private static SingletonClass instance;
    private int lastIndex = 10;
    public final static SingletonClass getInstance()
    if (instance == null) instance = new SingletoClass();
    return instance;
    public int getLastIndex() {
    return lastIndex;
    }1) This won't work since one could create a new SingletonClass. You need to add a private constructor. Also, because the constructor is private the class doesn't have to be final.
    2) Your design isn't thread-safe. You need to synchronize the access to the shared variable instance.
    public class SingletonClass {
        private static SingletonClass instance;
        private static Object mutex = new Object( );
        private int lastIndex = 10;
        private SingletonClass() { }
        public static SingletonClass getInstance() {
            synchronized (mutex) {
                if (instance == null) {
                    instance = new SingletonClass();
            return instance;
        public int getLastIndex() {
            return lastIndex;
    }if you are going to create an instance of SingletonClass anyway then I suggest you do it when the class is loaded. This way you don't need synchronization.
    public class SingletonClass {
        private static SingletonClass instance=new SingletonClass();
        private int lastIndex = 10;
        private SingletonClass() { }
        public static SingletonClass getInstance() {
            return instance;
        public int getLastIndex() {
            return lastIndex;
    }If you don't really need an object, then you could just make getLastIndex() and lastIndex static and not use the singleton pattern at all.
    public class SingletonClass {
        private static int lastIndex = 10;
        private SingletonClass() { }
        public static int getLastIndex() {
            return lastIndex;
    }- Marcus

  • How can i get the unitOfWork or the persisting object in to my listener???.

    hi,
    i have a listener class which extends SessionEventAdapter ....as shown below
    public class MyLister extends SessionEventAdapter{
    public void postCommitUnitOfWork(SessionEvent event) {
    System.out.println("POST COMMIT OF WORK");
    // How can i get the unitOfWork or the persisting object in to my listener???
    Another class makes use of this listener by adding the listener into a getEventManager() of a session ....
    public final class AetbProcessStatusClient {
    public static final void main(String[] args)
    {  Project project =   
    XMLProjectReader.read("META- INF/AetbProcessStatus.xml",
    Thread.currentThread().getContextClassLoader());
    DatabaseSession session = project.createDatabaseSession();
    MyLister myListener = new MyLister();
    session.getEventManager().addListener(myListener);
    session.login();
    UnitOfWork uow = session.acquireUnitOfWork();
    uow = session.acquireUnitOfWork();
    Vector vec =
    (Vector)uow.executeQuery("SQFunctionIdProcessStatus", AetbProcessStatus.class);
    AetbProcessStatus processStatus = new AetbProcessStatus();
    processStatus = (AetbProcessStatus)vec.get(0);
    processStatus.setRunStat('E');
    processStatus.setProgramSeqNo(10);
    uow.commit();
    now my question --> How can i get the unitOfWork or the persisting object in to my listener???....
    ie the object "processStatus" into my listener

    The SessionEvent's session (getSession()), should be the UnitOfWork. You can access the UnitOfWork or UnitOfWorkImpl methods to access the objects in the unit of work. getUnitOfWorkChangeSet() will return the changes made in the UnitOfWork.
    -- James : http://www.eclipselink.org

  • Error while activation the Datastore Object

    Hi folks,
    I am in SAP BASIS, so not aware of BI very much...can u help me in this,
    One user is getting error while activation the Datastore Object
    below is error log,
    (Green) Activation of Objects with Type DataStore Object
    (Green) Checking Objects with Type DataStore Object
    (Green) Checking DataStore Object DSO_TEST
    (Green) DataStore object DSO_TEST is consistent
    Table/view /BIC/VDSO_TEST2 (type VIEW) from DataStore object DSO_TEST saved
    Change log for DataStore object "DSO_TEST" saved successfully
    Writing of object catalog entries (TADIR)
    (RED) The creation of the export DataSource failed
    (RED) Error during the retrieval of the logon data stored in secure storage
    (RED) Error when creating the export DataSource and dependent Objects
    (RED) Error when activating DataStore Object DSO_TEST
    Thx. in advance
    Yash

    Hi Yash,
    Check out the below thread:
    [activation of the Datastore Object.|error in ODS activation/export datasource;
    Hope it helps you!
    Please reward points if helpful
    Manish

  • PowerPivot: data no longer available due to "the server object is not connected."

    Hi,
    I'm using Excel 2013 for building a PowerPivot model. Currently 2 table are inserted (txt files) which are related by a unique customer ID. 
    At for me random moments the connections with the files gets lost and no data is shown. Nevertheless, the number of rows and column headers are still visible. If I go the 'existing connections' and choose 'refresh' I got the following errror: "We couldn't
    refresh the connection, please go to existing connections and verify the connect to the file or server". If I try to edit the data ('edit connection') I see immediatly a preview of the date. But when I choose save I receive the following error: "unhandeld
    exception has occured in a component in your application ... The server object is not connected."
    Remarkebly I never had this problem with the same data in Excel 2010. Anyone an idea what could cause this problem and a way to work around this?
    Thanks in advance,
    Rolf

    I have the same error after installed Dec.9 updates, and then other thread suggest me remove them. it worked.
    Good luck. 

  • Error: The report source could not be retrieved from the state object.

    I have been trying to create a report in a JSF page. The relevant parts are below:
    Inside the JSP page, this is the code:
                  <jsp:useBean id="MyBean" class="com.nm.facade.rto.POJOViewerBean" scope="session" />
                    <jsp:setProperty name="MyBean" property="reportLocation" value="Report1.rpt" />
                   <v:reportPageViewer reportSource="#{MyBean.reportSource}"
                                           displayToolbarPrintButton="true"
                                           printMode="ActiveX"
                                           zoomPercentage="100"
                                           displayToolbarExportButton="true"
                                           displayToolbarRefreshButton="true"
                                           viewerName="My Viewer"
                   ></v:reportPageViewer>
    In the backing bean, this is the relevant code:
        public Object getReportSource() throws ReportSDKException
            if (propertiesChanged || reportSource == null)
                propertiesChanged = false;
                if (reportLocation == null)
                    throw new RuntimeException("The reportLocation property must be set before a report source is retrieved");
                ReportClientDocument rcd = new ReportClientDocument();
                rcd.setReportAppServer(ReportClientDocument.inprocConnectionString);
                rcd.open(reportLocation, 0);
                DatabaseController dbc = rcd.getDatabaseController();
                //Create the POJO collection and populate it with data
                ReportData[] data =
                  new ReportData("B.B.", "King", 6, new Date(25, 9, 16)),
                    new ReportData("Muddy", "Waters", 7, new Date(15, 4, 4)),
                    new ReportData("John Lee", "Hooker", 8, new Date(16, 8, 16)),
                    new ReportData("Otis", "Rush", 9, new Date(34, 4, 29)),
                    new ReportData("Buddy", "Guy", 10, new Date(36, 7, 30))
                //Create the result set from the collection of POJOs
                POJOResultSetFactory factory = new POJOResultSetFactory(ReportData.class);
                factory.setVerbose(true);
                POJOResultSet results = factory.createResultSet(data);
                ResultSetMetaData metaData = results.getMetaData();
                //Set the resultset as the report datasource
                      //Get the table name from the 'Set Datasource Location' dialog in the Crystal Reports designer
                String reportTable = "getReportDataDataSource";
                dbc.setDataSource(results, reportTable, reportTable);       
                IReportSource reportSource = rcd.getReportSource();
                if (reportSource == null)
                    throw new RuntimeException("Unable to get a report source.");
            return reportSource;
    In the CRConfig.xml, this is what is there:
    <?xml version="1.0" encoding="utf-8"?>
    <CrystalReportEngine-configuration>
        <reportlocation>../reports</reportlocation>
        <timeout>0</timeout>
        <ExternalFunctionLibraryClassNames>
             <classname></classname>
        </ExternalFunctionLibraryClassNames>
    </CrystalReportEngine-configuration>
    The report template 'Report1.rpt' is packaged under WEB-INF/reports in the war file.
    When I try to generate the report by accessing the JSF page, I am getting an error: "The report source could not be retrieved from the state object. "
    I am not sure what is wrong. Can someone help me in resolving this issue?
    Edited by: renshai on Jul 9, 2009 3:21 AM

    My formatting gets lost and the message looks unintelligible. After some experimentation, I found that if the message exceeds some length, the formatting is removed. Since I couldn't find any way to delete this post, I made another post with the same subject. Please ignore this post and help me to find a solution for the problem posted in the other thread with the same subject. Thanks in advance.

  • How can I refer to the PhotoShop Object library dynamically depend on the release of PhotoShop?

    Recently, I make a program, now I face a big program:
    I make the program by visual basic and photoshop script , but my client have different release of Photoshop, for example : photoshop 7.0 cs and cs2. I know every release of PhotoShop have ist own Object library, but in visual basic 6.0, I can only refer to one PhotoShop Object library. for example: if I refer to Photoshop 8.0 Object library, if my clients release of Photoshop is 7.0. there will be a error message : Run-time error '429 ( cant create object) Run-time error '430(Class does not support Automation or does not support expected interface), How can I refer to the PhotoShop Object library dynamically depend on the release of PhotoShop?
    my email is : [email protected] .
    any suggestion?

    Please read, and reply back here with information https://forums.adobe.com/thread/1499014
    -and try some steps such as changing browsers and turning off your firewall for downloads

  • The Thread which won't let go...

    I posted very late last night and those who responded were a big help. Still, even though I changed my code I'm worked my way right around into a big circle and the exact same stopping point. Here is some sample code to try to simplify my complication.
    I'm attempting to complete an assignment (due in a few hours) lol... which is supposed to be an "application" not an "applet". It's a lesson in multi-threading. Supposidly there is a main thread which drives everything, several processing threads and a thread which prompts for input. I've got the Thread which prompts for input working just fine as well as the others. However, whenever one of the processing threads begins to process the data, I get no further DOS prompt from my input object until that Thread has completed. I'm going nuts trying to figure out how not to have this happen.
    I'll make an attempt at a simplified version of what's happening below:
    class mainThread impliments Runnable(){
        public void run(){
            while(true){
               //call inputThread object
               dataprocessor();
               //call processorThread object
        public void dataProcessor(){
            //processes data & calls on other methods & objects
            //to help
    class processorThread impliments Runnable(){
    //several of these objects are created to process data
    class InputThread impliments Runnable(){
    //has two methods as given to us by instructor
        public String method1(){
            //involks prompt requesting Strings or characters from user
            //  returns String
        public int method2(){
            //involks prompt requesting integer from user
            //  returns int
    }The problem is when processorThread object is called, everything stops and waits for it to complete. Help!!

    A thread has 3 elements;-
    - start()
    - run()
    - stop()
    controlled by boolean values if(myInt==myCondition){
      myThread.stop();   // method is depricated as it may not stop 'cleanly' and thrfr = memory prob's
      nowPutTheCatOut - etc
    // Better method;-
    public void start() {
    if(myCondition=false){
      myThread.run();
    // X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*X*Hope that helps

Maybe you are looking for

  • Process InfoPackage based on a condition in Process Chain

    Hi, I would like to include a Function Module in my Process Chain.Based on the output of the Function Module (example Flag - 'A','B','C') I would like to load data from Infopackage. Could you please suggest the best possible solution. Thanks, Nimai

  • How to set App Module Config parameters at run time?

    Hi, I am using jdev 11.1.1.3 and developed a Fusion Web Application application. Before moving the code to production I want to have a stress testing where I should be able to set the application module configuration parameters at run time. So I woul

  • Doubt in formatted search query

    HI all This is the query i have seen in the forum Regarding linking of the UDF size in BOM to Production Order, you will need to create a formatted seach as the tables where the UDF exists are different. In case your UDF is at the row level then use

  • Commissions report

    I am trying to run my commissions report in SAP, but it keeps coming back saying no data.  I have processed tons of invoices all with  a salesperson assigned.  my settings had both the items and customer checkboxes marked.  Why can't i get even one i

  • E52 CAN USE AS A MODEM TO PC?

    hi guys , is nokia E52 can use as  a modem in PC?  thanks