Thread as object

Seems to be very easy question: a thread is an object derived from the Thread class. This makes me think threads are 'common' objects that obey to the rules of java object orientation. Suppose now that we have a program to accept tcp connections, like the one bellow:
   ServerSocket ss = new ServerSocket(20000);
   while (true) {
        Socket so = ss.accept( );
        MyThread mt = new MyThread(so);
        mt.start( );
   }MyThread is a class that extends Thread. It can have code like that:
    class MyThread extends Thread {
          Socket so = null;
          MyThread (Socket so) {
              this.so = so;
          public void run( ) {
              -------- long time processing
    }Now, the question: if the run method in the thread lasts for a long time we can imagine that another connection will be open while the first thread is still running. In this situation the variable mt from the first code will be overriden by a reference to the new thread leaving the former one without any program references. Will this make the first thread available to the garbage collector or are threads such special objects that can live without any references to them (except those from the jvm)?
Shall we have a pool of "living" threads, in order to keep references to them?
Thanks,
Ricardo

The gc will not remove the thread. The thread is (at
least) referenced by the thread group.So, Kaj, any thread is allways a member of a thread group? Is there a first or primitive thread group that any thread is a member of?
Thanks for your reply,
Ricardo

Similar Messages

  • Problems Passing Thread a object

    Hello,
    I am trying to pass a Thread a object to modify. I get the error :
    local variable dateLabel is accessed from within inner class; needs to be declared final
                            makeClock(dateLabel);
                                              ^however I want the Thread to modify the object...so if I declare it final I won't be able to
    change the object. How can I pass a Thread a object to work on with out getting this error.
    here are parts of the code....
    //this is from the constructor
    JLabel dateLabel = new JLabel();
    clockPanel.add(dateLabel);
    startThread(dateLabel);
    //this is from a method outside the constructor -- this starts the new thread
    private void startThread(JLabel dateLabel) {
      Runnable r = new Runnable() {
        public void run() {
          makeClock(dateLabel);
      clockThread = new Thread(r, "Clock");
      clockThread.start();
    //this is work the tread is supposed to do
    public void makeClock(JLabel dateLabel){
      MyCalendar myc = new MyCalendar();
      Date myDate;
      myDate = myc.getDate();
      dateLabel.setText((new SimpleDateFormat("E MMM dd hh:mma")).format(myDate));
    }thanks,
    jd

    here is what i came up with, it doesnt use final and it works... but is it the proper
    way to have a thread work on a object?
    thanks,
    jd
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    /* looks like to start a new thread just write a new class in the same class?
       then you can have it a modify a object */
    public class JThread extends JFrame{
         String testString = null;
         JLabel myLabel = new JLabel("Start");
         public JThread(){
              JPanel mainPanel = new JPanel();
              mainPanel.setPreferredSize(new java.awt.Dimension(200,200));
              getContentPane().add(mainPanel);
              mainPanel.add(myLabel);
              pack();
                 setSize(200,200);
                 setVisible(true);
              myThread1();
              myThread2();
         private void myThread1(){
              Thread t = new startThread();
              t.start();
         private void myThread2(){
              Thread t2 = new startThread2();
              t2.start();
         public class startThread extends Thread{
              public void run(){
                   doIt();
              private void doIt(){
                   int i = 1;
                   while(i>0){
                        testString = new String("hi");
                        myLabel.setText(testString);
         public class startThread2 extends Thread{
              public void run(){
                   doIt2();
              private void doIt2(){
                   int i = 1;
                   while(i>0){
                        testString = new String("Bye");
                        myLabel.setText(testString);
         public static void main(String[] args){
              JThread jt = new JThread();
    }

  • Under CentOS 6 x64, Java Thread.sleep()/Object.wait() will be influenced.

    Under CentOS 6 x64, Java Thread.sleep()/Object.wait() will be influenced while changing OS time.
    I found a BUG in java bug list. The bug id is 6311057 with fixed status. But I find it still existing.
    Under CentOS6 x64 platform, on JDK1.6.0_33, the bug still exists.
    But under CentOS5 x64 platform, on same JDK, the problem does not exist.
    Could anyone give me help? Thanks.
    The bug's link is http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6311057
    Edited by: user10222290 on 2012-6-13 下午9:22

    user10222290 wrote:
    One server could want to synchronize it's OS time with another server when they connected each other for some business reasons. I have 3 computers running pretty much continuously with time synchronised from one of the internet time servers. They never seem to be more than about 1/10 th second apart and any time corrections are very very small.
    Some threads have started to run before changing OS time, so these thread's sleep process will be influenced sometime seriously.I understand that but I would only expect this to be a problem when there is a significant change to the OS time. If each server is synchronized to a time server then the time corrections will be very very small.
    If OS time was turned back some days, these thread could not wake up untill some days passed.Agreed but why would the "OS time be turned back some days" ?
    This whole problem seems to me to arise because the servers are not time synchronized. Now I understand that there may be concerns about the security of external time servers but it is easy enough to make one of the local servers a master and act as a time server to the others.
    I have a small server that typically services some 30 or so external clients. I don't have any control over the clients and do not know anything about the setting of their system clocks. The clients send a time signal as part of a heartbeat and from this the server keeps track of the local time on each client and compensates for any difference when writing logs. I have seen this difference as big as 4 months but the compensation corrects it to within about a second. No adjustment of clocks is required for this.
    I still don't see this 'bug' as a serious bug. I just see a design problem to be solved without changing the OS time on any computer. I know this can be done since I do it. The only problem I see is if you want an accuracy of better than about 20 mS but that does not seem to be required for your system.
    Note - if Oracle accept your new bug report it could take years to fix even if lots of people vote for it to be fixed.

  • Multiple threads access Object

    Hi. I have no experience with thread. I just decided to learn it with writing some application. I have not started to do programing yet. I just trying to identify some main problems which I think I will encounter when I start programming.
    And this is my problem. I have 1 parent thread, 4 child threads and one Static Object. For threads constantly a access Static object just for reading. I think I can make it not syncronized because child threads only read the object. The perant thread does a different job. I needs to access this object and change the string which the child object will read. Now I see a problem here. If I make it not syncronized the child threads will get bad data. I just can't get how I can make object locked only when parent thread is using it. If parent does not use it the child can freely read data from it. Any ideas.

    Thanks for your advice. Now I have read the java thread tutorial and I have some understanding how threads are workin. However I am still facing one problem.
    imagine this. I have one Thread Produce and 5 Threads Consumers.
    The produce and Consumer access GlobalString object.
    The produce puts the string into object and consumer reads it.
    The problem is that in order for wait() and notify() to work both methods of GlobalString(getString.,setString) must be syncronized. What I want to achieve is that only setString in syncronized and then when it is done
    all 5 Consumer Threads can run getString at same time. If I make this method Syncronizable it will work much slower. I just want to make sure that reading of that string is fast. Can this be done or not?
    this is my code
    public class GlobalString {
    static String stream = "this is the steam";
    public GlobalString() {
    public synchronized String get() {
    try {
    System.out.println("waiting");
    wait();
    System.out.println("Stop waitng");
    catch (InterruptedException ex) {
    System.out.println(ex.toString());
    return stream;
    public synchronized void set(String set) {
    stream = set;
    notifyAll();
    public class Consumer extends Thread{
    private GlobalString gs = null;
    public Consumer(GlobalString gsa) {
    gs = gsa;
    public void run() {
    try {
    System.out.println("thread 2");
    gs.get();
    System.out.println("thread 2 end");
    catch (Exception ex) {
    System.out.println(ex.toString());
    public class GlobalString {
    static String stream = "this is the steam";
    public GlobalString() {
    public synchronized String get() {
    try {
    System.out.println("waiting");
    wait();
    System.out.println("Stop waitng");
    catch (InterruptedException ex) {
    System.out.println(ex.toString());
    return stream;
    public synchronized void set(String set) {
    stream = set;
    notifyAll();
    public class Producer extends Thread{
    private GlobalString gs = null;
    public Producer(GlobalString gsa) {
    gs = gsa;
    public void run() {
    try {
    Thread.sleep(3000);
    gs.set("test");
    System.out.println("output");
    } catch(Exception e) {
    System.out.println(e.toString());
    }

  • Very Basic Question on Threads and Object Manipulation between classes

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

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

  • Thread safe object cache

    The case:
    I have a case where I hold configuration about a web page in an xml-file. The configuration is cached in memory on first request then I retrieve the configuration from memory on every following request. If the configuration in the xml-file changes between requests I will release the current configuration from memory and renew it by reading from the file.
    Since we are talking about http requests all this will happen in a heavy loaded multithreaded environment.
    The current solution:
    +public class ConfigFile {+
    private static final ConfigCache REGISTRY;
    +static {+
    REGISTRY = ModuleRegistry.create();
    +}+
    +public static Element getConfigElement(final String configKey) {+
    Element configElm = null;
    +if(configFileIsChanged()) {+
    REGISTRY.clear();
    +}+
    +if((configElm = REGISTRY.get(configKey)) == null) {+
    +... //Reload configuration from xml-file+
    REGISTRY.put(configKey, configElm);//and save to registry
    +}+
    return configElm;//Return config data as an xml-element
    +}+
    +... //Class impl..+
    +//This inner class holds the configuration as dom element parts+
    +private static class ConfigCache {+
    +private HashMap<String, Element> _moduleRegistry;+
    +public synchronized void put(final String key, final Element elm) {+
    _moduleRegistry.put(key, elm);+
    +}+
    +public synchronized Element get(final String module) {+
    +return _moduleRegistry.get(key);+
    +}+
    +public synchronized void clear() {+
    _moduleRegistry.clear();+
    +}+
    +public static ConfigCache create(){+
    return new ConfigCache();
    +}+
    +}+
    +}+
    Since the registry is declared as a class variable in the ConfigFile class I handle the put and get operations to it by synchronizing the access.
    The problem/question:
    Is if this is enough to handle possible threading issues when it comes to invalidating the registry. What happens if some thread tries to "get" from the registry when another just cleared it? I guess it needs to wait until it's reloaded, right?
    Regards
    Johannes

    I wasn't clear enough in my previous post. Sorry for that.
    The code will be executed in a servlet/JSP environment but it's not really relevant in this case except for the fact that there will be multiple threads accessing this code.
    Think of it as an in memory data storage with information that will be read from the memory. The memory in this case is implemented as a static HashMap (the ConfigCache). I've wrapped it in the ConfigCache class since I want to synchronize the access to the put and get. All threads have access to the configuration file through the static method call ConfigFile.getModuleElement(somElementName);. This method is not synchronized.
    Suppose we have 20 threads accessing this code concurrently. I'm not sure how the code will behave when this executes. My guess is that the critical parts are when one thread clears the HashMap, another tries to put something to the Map and another tries to get something.
    I made an assertation test where I expected different results from 5 randomly executed web requests with 20 active threads reading and writing to the Map (the ConfigCache). It succeeds but I'm still not sure if I'm on the right track.
    I've read a lot about this but I have not found any material describing this as clearly as I want it. In most cases they only explain how to use synchronized blocks and methods.
    Are you with me or do you still think this belong in the servlet forum? Maybe it does?
    BTW. How do I use code tags?

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

  • Shared Objects for Threads

    Hi,
    Currently studying for SCJP exam and wondering is there a different between the following codes
    public class Test extends Thread
    static Object obj = new Object();
    static int x, y;
    public void run()
       synchronized(obj)
         for(;;)
          x++; y++; System.out.println(x+" "+y);
    public static void main(String[] args)
       new Test().start();
       new Test().start();
    }and
    public class Test extends Thread
    Object obj = new Object();
    static int x, y;
    public void run()
       synchronized(obj)
         for(;;)
          x++; y++; System.out.println(x+" "+y);
    public static void main(String[] args)
       new Test().start();
       new Test().start();
    In the first code example, is there a shared object between created threads and the second example, is their still a shared object between threads or is a new object created for each thread?
    Cheers!

    Hi,
    In first case, you are acquiring lock on a static object that is of course shared (basic concept) by all instances(of Test). So, for any thread of any instance(of Test) to execute the synchronized block has to wait till any other thread of any other instance(of Test) comes out of synchronized block. It means, all the instances (of Test) are synchronized. In this scenario, you have infinite for loop within synchronized block and you are starting two threads. The thread which enters the synchronized block first will keep on executing and the other thread will never get chance to enter synchronized block.
    In second case, as you are acquiring lock on an object, all the threads of a particular instance (of Test) will be synchronized. In this scenario, again you have infinite for loop within synchronized block and you are starting two threads on two different instances. Hence, both the threads will keep on executing in parallel.
    I hope, you have already executed both the examples and observed output. And also hope that the above explanation will help you to understand the difference between two scenarios.
    Note: Use System.out.println(Thread.currentThread().getName() + " " + x + " " + y); in your synchronized block to track which thread is printing the output.
    Thanks,
    Mrityunjoy

  • Passing objects to running threads..

    May anybody give me an idea on how to pass an object to an already running thread??
    i only know how to pass an object to the thread's constructor.

    I guess you are trying to assign a variable dynamically. What you can do is a keep a reference in your thread class (you may have probably done it because you have mentioned about passing an object to your threads constructor). Then give a public setter method to assign an object to that variable. Then you can change that even after you invoke start() of your Thread object.
    example:
    public class MyThread extends Thread{
    private Object obj;
    public void setObject(Object obj){
    this.obj = obj;
    public void run(){
    //your code for the thread
    Then from the class you invoke the thread you can do the following:
    MyThread t = new MyThread();
    t.start();
    Object obj = "your object";
    t.setObject(obj);
    Note: However if your thread is not alive when you assign the object then there will be no use of the passed object to the code inside run() method

  • Multi Threading..on object locking

    when a synchronised method of an object is invoked by a thread that object gets locked. can another thread invoke unsynchronized method of the same object? howz it possible..if it is possible..pl give the rationale behind this..

    Yes it can. And the reason is part of your homework assignment.

  • Problem with painting/threads/ProgressMonitor

    Hello,
    I'll try to be clear, ask me anything if it isn't. I have two threads, one that downloads some selected webpages, and the other that reads them. In the thread that reads, there is a ProgressMonitor object, which indicate how many webpages have been read.
    I created a JUnit test which works as expected. One thread downloads, the other reads and a nice little progress monitor appears and everything works.
    I transfered the code (the part of the code starting the thread that reads, which starts the thread that downloads) into the main application. The threads are working and the ProgressMonitor appears, but it does not draw the components (there is no label, progress bar, button etc...). I can't seem to find the problem. I think it is caused by the threads or synchronized methods, I am not sure as I am no expert with threads. Once the threads have finished running, the components of the ProgressMonitor appears. So I guess that the threads are blocking the (re)painting of the application, but I can't figure why. Im using Thread.yield() quite often. Priorities problem ? Here some parts of the code :
    JUnit Test code :
         public synchronized void testHarvest() {
              JFrame frame = new JFrame("Super");
              frame.setVisible(true);
              Harvester harvester = new Harvester(
                        frame,
                        new Rule());
              Thread harvest = new Thread(harvester);
              harvest.start();
              try {
                   harvest.join();
              } catch (InterruptedException ie) {}
    ...Main application :
    Code:
    public class Gui extends JFrame implements ComponentListener {
       private static JFrame mMotherFrame = null;
        public Gui() {
            mMotherFrame = this;
        private class GuiActionRealize {
              public synchronized void getFromWeb() {
                   Harvester harvester = new Harvester(
                             mMotherFrame,
                             new Rule());
                   Thread harvest = new Thread(harvester);
                   harvest.start();               
                   try {                    
                        harvest.join();
                   } catch (InterruptedException ie) {}
    }Harvester :
    Code:
    public class Harvester implements Runnable {
      private JFrame mMotherFrame;
      private ProgressMonitor mMonitor;
    public Harvester(JFrame owner, IRule subjectRule) {
       mMotherFrame = owner;
        public void find() {
        mMonitor = new ProgressMonitor(mMotherFrame, "Downloading from the Internet.", "", 1, mAcceptedURLs.size());
         mMonitor.setMillisToDecideToPopup(0);
         mMonitor.setMillisToPopup(0);
    public void run() {
      find();
      mHarvested = harvest();
      mFinished = true;
      Thread.yield();
    public List harvest() {
      download = new DownloadThread(this, mAcceptedURLs);
      Thread downthread = new Thread(download);
      downthread.start(); int i = 0;
      while (!mMonitor.isCanceled()) {
          while (download.getDownloadedDocuments().isEmpty()) {
               try {
                       Thread.yield();
                       Thread.sleep(300);
                } catch (InterruptedException ie) {}
           mMonitor.setNote("Downloading decision " + i);
           mMonitor.setProgress(mMonitor.getMinimum()+ ++i);
           } // end while(!cancel)
           download.kill();
           return mHarvested;
    }I'm very puzzled by the fact that it worked in the JUnit Case and not in the application.
    I can see that the thread that is responsible for drawing components is not doing his job, since that the mother frame (Gui class) is not being repainted while the harvest/download threads are working. That's not the case in the JUnit case, where the frame is being repainted and everything is fine. This is the only place in the application that I'm using threads/runnable objects.
    I also tried making the Gui class a thread by implementing the Runnable interface, and creating the run method with only a repaint() statement.
    And I tried setting the priority of the harvest thread to the minimum. No luck.
    If you need more info/code, let me know, Ill try to give as much info as I can.
    Thank you

    Why are you painting the values yourself? Why don't you just add the selected values to a JList, or create a container with a GridLayout and add a JLabel with the new text to the container.
    Every time you call the paintComponent() method the painting gets done from scratch so you would need to keep a List of selected items and repaint each item every time. Maybe this [url http://forum.java.sun.com/thread.jsp?forum=57&thread=304939]example will give you ideas.

  • No externally managed transaction is currently active for this thread

    Got the following exception after updating an entity bean and call persist method. Code the given below the exception.
    Exception [TOPLINK-23010] (Oracle TopLink - 10g Release 3 (10.1.3.0.0) (Build 060118)): oracle.toplink.exceptions.TransactionException
    Exception Description: No externally managed transaction is currently active for this thread
    public Object persistEntity(Object entity) {
    em.flush();
    em.persist(entity);
    return entity;
    private void modifyUser (Iuser user, String newHandle, Hashtable userDetails) throws UnknownException, WarningException {
    if (user == null) {
    throw new WarningException (new CatalogHelper("ITOOLS_000015", "to modify a user"));
    boolean handleUpdate = false;
    if ((newHandle != null) && !newHandle.equals("^\\s*$")) {
    handleUpdate = true;
    String oldHandle = user.getUserhandle();
    if (handleUpdate && oldHandle.equalsIgnoreCase(newHandle)) {
    handleUpdate = false;
    if (!handleUpdate && (userDetails == null) || (userDetails.size() == 0)) {
    return;
    if (handleUpdate) {
    userDetails.put("userhandle", newHandle);
    IToolsUtil.validateInputData("iuser", userDetails, false);
    if (handleUpdate) {
    userDetails.remove("userhandle");
    System.out.println("handleUpdate " + handleUpdate);
    // For User admin, handle, isactive, isadmin cannot be changed.
    if (oldHandle.equals("admin")) {
    if (handleUpdate) {
    throw new WarningException (new CatalogHelper("ITOOLS_000045", "Handle"));
    String active = (String)userDetails.get("isactive");
    if ((active != null) && !active.equals("Yes")) {
    throw new WarningException (new CatalogHelper("ITOOLS_000045", "Is Active"));
    String admin = (String)userDetails.get("isadmin");
    if ((admin != null) && !admin.equals("Yes")) {
    throw new WarningException (new CatalogHelper("ITOOLS_000045", "Is Admin"));
    System.out.println("user transaction started");
    if (handleUpdate) {
    FinderMethods fm = new FinderMethods();
    try {
    fm.findByUserHandle(em, newHandle);
    throw new WarningException (new CatalogHelper("ITOOLS_000043", newHandle));
    } catch (ObjectNotFoundException onfe) {
    user.setUserhandle(newHandle);
    System.out.println("User handle modified");
    } catch (SQLException se) {
    se.printStackTrace();
    throw new UnknownException (new CatalogHelper("ITOOLS_100000", new Object[]{"modifyUser", se.getMessage()}));
    String lname = (String)userDetails.get("userlname");
    if (lname != null) {
    user.setUserlname(lname);
    String fname = (String)userDetails.get("userfname");
    if (fname != null) {
    user.setUserfname(fname);
    String email = (String)userDetails.get("useremail");
    if (email != null) {
    user.setUseremail(email);
    String passwd = (String)userDetails.get("userpasswd");
    if (passwd != null) {
    user.setUserpasswd(passwd);
    String active = (String)userDetails.get("isactive");
    if (active != null) {
    user.setIsactive(active);
    String admin = (String)userDetails.get("isadmin");
    if (admin != null) {
    user.setIsactive(admin);
    System.out.println("details are updated");
    persistEntity(user);
    System.out.println("committed");
    How to resolve this issue? I am using Jdeveloper 10.1.3.0.4 (SU4)
    regds
    -raju

    The stack trace is given below. This exception is occured at "em.flush()" method. I even tried removing em.flush() method. Even then I got the same exception.
    I tried a different way of overcome this problem. Used UserTransaction instance say "ut" before create / modify the entity bean and later comitted. In that case I am not getting any exceptions. However, commit is happening only when new instance is created, commit works, but modification of an existing instance, commit is not working. Looks like there is some serious problem with EJB 3.0 in OC4J. Basic functionality is not working.
    Stack trace when flush method is called:
    Local Exception Stack:
    Exception [TOPLINK-23010] (Oracle TopLink - 10g Release 3 (10.1.3.0.0) (Build 060118)): oracle.toplink.exceptions.TransactionException
    Exception Description: No externally managed transaction is currently active for this thread
         at oracle.toplink.exceptions.TransactionException.externalTransactionNotActive(TransactionException.java:98)
         at oracle.toplink.internal.ejb.cmp3.transaction.base.JTATransactionWrapper.checkForTransaction(JTATransactionWrapper.java:39)
         at oracle.toplink.internal.ejb.cmp3.base.EntityManagerImpl.checkForTransaction(EntityManagerImpl.java:322)
         at oracle.toplink.internal.ejb.cmp3.base.EntityManagerImpl.getActiveUnitOfWork(EntityManagerImpl.java:314)
         at oracle.toplink.internal.ejb.cmp3.base.EntityManagerImpl.flush(EntityManagerImpl.java:164)
         at com.itools.vs.model.session.AdminSessionBean.persistEntity(AdminSessionBean.java:57)
         at com.itools.vs.model.session.AdminSessionBean.createUser(AdminSessionBean.java:124)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at com.evermind.server.rmi.RmiMethodCall.run(RmiMethodCall.java:53)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
         at java.lang.Thread.run(Thread.java:595)
    Stack trace when persist method is called:
    Local Exception Stack:
    Exception [TOPLINK-23010] (Oracle TopLink - 10g Release 3 (10.1.3.0.0) (Build 060118)): oracle.toplink.exceptions.TransactionException
    Exception Description: No externally managed transaction is currently active for this thread
         at oracle.toplink.exceptions.TransactionException.externalTransactionNotActive(TransactionException.java:98)
         at oracle.toplink.internal.ejb.cmp3.transaction.base.JTATransactionWrapper.checkForTransaction(JTATransactionWrapper.java:39)
         at oracle.toplink.internal.ejb.cmp3.base.EntityManagerImpl.checkForTransaction(EntityManagerImpl.java:322)
         at oracle.toplink.internal.ejb.cmp3.base.EntityManagerImpl.getActiveUnitOfWork(EntityManagerImpl.java:314)
         at oracle.toplink.internal.ejb.cmp3.base.EntityManagerImpl.persist(EntityManagerImpl.java:74)
         at com.itools.vs.model.session.AdminSessionBean.persistEntity(AdminSessionBean.java:57)
         at com.itools.vs.model.session.AdminSessionBean.createUser(AdminSessionBean.java:123)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at com.evermind.server.rmi.RmiMethodCall.run(RmiMethodCall.java:53)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
         at java.lang.Thread.run(Thread.java:595)

  • EXECUTE permission denied on object 'xp_sqlagent_notify', database 'mssqlsystemresource', schema 'sys'.

    I'm trying to create a new subscriptions on an existing report and get the following error.
    An internal error occurred on the report server. See the error log for more details. (rsInternalError) Get Online Help
    Get Online Help
    EXECUTE permission denied on object 'xp_sqlagent_notify', database 'mssqlsystemresource', schema 'sys'.
    I ran the following that was suggested in http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=17774&SiteID=1. But still I get the same error. Do I need a reboot or restart of the services?
    The only log file information I can find contains the following.
    System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: An internal error occurred on the report server. See the error log for more details. ---> Microsoft.ReportingServices.Diagnostics.Utilities.InternalCatalogException: An internal error occurred on the report server. See the error log for more details. ---> System.Data.SqlClient.SqlException: EXECUTE permission denied on object 'xp_sqlagent_notify', database 'mssqlsystemresource', schema 'sys'.
       --- End of inner exception stack trace ---
       at Microsoft.ReportingServices.WebServer.ReportingService2005.ListSchedules(Schedule[]& Schedules)
       at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
       at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
       at Microsoft.SqlServer.ReportingServices2005.ReportingService2005.ListSchedules()
       at Microsoft.SqlServer.ReportingServices2005.RSConnection.ListSchedules()
       at Microsoft.ReportingServices.UI.SharedScheduleDropDown.EnsureSchedulesAreLoaded()
       at Microsoft.ReportingServices.UI.SharedScheduleDropDown.SharedScheduleDropDown_Load(Object sender, EventArgs e)
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
    aspnet_wp!ui!1!17/10/2006-08:44:26:: e ERROR: Exception in ShowErrorPage: System.Threading.ThreadAbortException: Thread was being aborted.
       at System.Threading.Thread.AbortInternal()
       at System.Threading.Thread.Abort(Object stateInfo)
       at System.Web.HttpResponse.End()
       at System.Web.HttpServerUtility.Transfer(String path, Boolean preserveForm)
       at Microsoft.ReportingServices.UI.ReportingPage.ShowErrorPage(String errMsg) at    at System.Threading.Thread.AbortInternal()
       at System.Threading.Thread.Abort(Object stateInfo)
       at System.Web.HttpResponse.End()
       at System.Web.HttpServerUtility.Transfer(String path, Boolean preserveForm)
       at Microsoft.ReportingServices.UI.ReportingPage.ShowErrorPage(String errMsg)
    aspnet_wp!extensionfactory!e!17/10/2006-09:35:13:: w WARN: The extension Report Server Email does not have a LocalizedNameAttribute.
    aspnet_wp!extensionfactory!e!17/10/2006-09:35:13:: w WARN: The extension Report Server FileShare does not have a LocalizedNameAttribute.
    aspnet_wp!ui!e!17/10/2006-09:35:13:: e ERROR: System.Web.Services.Protocols.SoapException: An internal error occurred on the report server. See the error log for more details. ---> Microsoft.ReportingServices.Diagnostics.Utilities.InternalCatalogException: An internal error occurred on the report server. See the error log for more details. ---> System.Data.SqlClient.SqlException: EXECUTE permission denied on object 'xp_sqlagent_notify', database 'mssqlsystemresource', schema 'sys'.
       --- End of inner exception stack trace ---
       at Microsoft.ReportingServices.WebServer.ReportingService2005.ListSchedules(Schedule[]& Schedules)
    aspnet_wp!ui!e!17/10/2006-09:35:13:: e ERROR: HTTP status code --> 200
    I cannot find any other error log.
    Can anybody help?
    Tuesday, October 17, 2006 8:49 AM
    Reply
    |
    Quote
    All replies
    0
    Sign in to vote
    Sorry for the late reply. Try this: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=662319&SiteID=1
    Thursday, November 16, 2006 2:51 AM
    Reply
    |
    Quote
    Answerer
    0
    Sign in to vote
    GRANT EXECUTE ON master.dbo.xp_sqlagent_notify TO RSExecRole
    GO
    solved my problem.
    Proposed as answer by
    Christopher D. Stover
    Monday, September 16, 2013 6:52 PM
    Monday, September 16, 2013 6:51 PM
    Reply
    |
    Quote
    0
    Sign in to vote
    Tried that but no joy. Found this post on SQLServerCentral, solved our issue which mimic's the posters issue.  Just adding here as this is the first result in our search.
    Look for Topic452669-150-1
    There are a number of places I found with the information in the following
    link:
    http://phew-meme.blogspot.com/2007/10/reporting-service-on-report.html
    In
    my specific case, the RsExecRole role in both the "master" and "msdb" databases
    had had both the "NT Authority\Network Service" and "NTAuthority\System" logins
    removed from its members (the RSExecRole had had all its members removed by
    someone doing some maintenance). I compared another Reporting Services
    installation on another server after reading information in the above
    link.
    Steps:
    1. In Mangement Studio connect to the SQL Server instance
    on which Reporting Services runs.
    2. Databases > system Databases
    3.
    master > Security > Roles > RSExecRole (then add whatever logins are
    required... check in the ReportServer or ReportServerTempDB databases if you're
    not sure)
    4. msdb > Security > Roles > RSExecRole (add the same
    logins you did to the master DB)
    In the end you need the same logins in
    RSExecRole role for the master, msdb, ReportServer, and ReportServerTempDB
    databases. ("ReportServer" is the default Reporting Services database name, in
    case that's not clear ;)
    Monday, March 31, 2014 1:24 PM
    Reply
    |
    Quote
    if (!$.Microsoft) $.Microsoft = {};
    if (!$.Microsoft.Mtps) $.Microsoft.Mtps = {};
    if (!$.Microsoft.Mtps.NetReflectorInit)
    $.Microsoft.Mtps.NetReflectorInit = {
    surveyUrl: 'http://support.microsoft.com/common/survey.aspx?scid=sw%3ben%3b3763&altstyle=narrow&renderoption=overridedefault&theme=tech&url=http://social.technet.microsoft.com/Forums/en-US/3fcc7b54-ce84-48c2-9004-baaac07f2515/execute-permission-denied-on-object-xpsqlagentnotify-database-mssqlsystemresource-schema?forum=sqlreportingservices&P0=055ccfc1-78f5-46ff-8171-33f8ff760a7c',
    throttleRate: "5.00",
    privacyStatementText: "Privacy statement",
    trackerWindowText: "Please do not close this window.Thank you! The survey will appear here when you've completed your visit, so please do not close this window.",
    logoUrl: 'https://www.microsoft.com/library/svy/sto/technet_logo.gif',
    closeButtonUrl: 'https://www.microsoft.com/library/svy/sto/technet-close.gif',
    topBarUrl: 'https://www.microsoft.com/library/svy/sto/top-stripe.gif',
    bottomBarUrl: 'https://www.microsoft.com/library/svy/sto/bottom-stripe.gif',
    blankPage: 'https://social.technet.microsoft.com/forums/blank.htm',
    showSurveyToComscoreUser: 'no'
    setTimeout("Forums.loadScript('https://i1.social.s-msft.com/Forums/resources/NetReflector/NetReflector.js?cver=0%0d%0a')", 1000);
    Microsoft is conducting an online survey to understand your opinion of the Technet Web site. If you choose to participate, the online survey will be presented to you when you leave the Technet Web site.
    Would you like to participate?
    Privacy statement
    © 2015 Microsoft. All rights reserved.
    Newsletter|Contact Us|Privacy Statement|Terms of Use|Trademarks|Site Feedback
    TechNet
    Products
    IT Resources
    Downloads
    Training
    Support
    Products
    Windows
    Windows Server
    System Center
    Internet Explorer
    Office
    Office 365
    Exchange Server
    SQL Server
    SharePoint Products
    Lync
    See all products »
    Resources
    Curah! curation service
    Evaluation Center
    Learning Resources
    Microsoft Tech Companion App
    Microsoft Technical Communities
    Microsoft Virtual Academy
    Script Center
    Server and Tools Blogs
    TechNet Blogs
    TechNet Flash Newsletter
    TechNet Gallery
    TechNet Library
    TechNet Magazine
    TechNet Subscriptions
    TechNet Video
    TechNet Wiki
    Windows Sysinternals
    Virtual Labs
    Solutions
    Networking
    Cloud and Datacenter
    Security
    Virtualization
    Updates
    Service Packs
    Security Bulletins
    Microsoft Update
    Trials
    Windows Server 2012 R2
    System Center 2012 R2
    Microsoft SQL Server 2012 SP1
    Windows 8.1 Enterprise
    See all trials »
    Related Sites
    Microsoft Download Center
    TechNet Evaluation Center
    Drivers
    Windows Sysinternals
    TechNet Gallery
    Training
    Training Catalog
    Class Locator
    Microsoft Virtual Academy
    Free Windows Server 2012 courses
    Free Windows 8 courses
    SQL Server training
    e-Learning overview
    Certifications
    Certification overview
    MCSA: Windows 8
    Windows Server Certification (MCSE)
    Private Cloud Certification (MCSE)
    SQL Server Certification (MCSE)
    Other resources
    TechNet Events
    Second shot for certification
    Born To Learn blog
    Find technical communities in your area
    Support options
    For small and midsize businesses
    For enterprises
    For developers
    For IT professionals
    From partners
    For technical support
    Support offerings
    For home users
    More support
    Microsoft Premier Online
    Microsoft Fix It Center
    TechNet Forums
    MSDN Forums
    Security Bulletins & Advisories
    International support solutions
    Log a support ticket
    Not an IT pro?
    Microsoft Customer Support
    Microsoft Community Forums
    var railItems = ["/Forums/en-US/rightrailannouncement/Technet/1794d07f-9d4e-4dc0-8c1c-8bfe9d5e0bce"];
    var pageData = {"validUser":false,"autoSubscribe":false};
    var userEmailConfigured = false;
    $(document).ready(function () {
    Forums.ThreadPage.wirePageElements('Search forum questions');

    Tried that but no joy. Found this post on SQLServerCentral, solved our issue which mimic's the posters issue.  Just adding here as this is the first result in our search.
    Look for Topic452669-150-1
    There are a number of places I found with the information in the following
    link:
    http://phew-meme.blogspot.com/2007/10/reporting-service-on-report.html
    In
    my specific case, the RsExecRole role in both the "master" and "msdb" databases
    had had both the "NT Authority\Network Service" and "NTAuthority\System" logins
    removed from its members (the RSExecRole had had all its members removed by
    someone doing some maintenance). I compared another Reporting Services
    installation on another server after reading information in the above
    link.
    Steps:
    1. In Mangement Studio connect to the SQL Server instance
    on which Reporting Services runs.
    2. Databases > system Databases
    3.
    master > Security > Roles > RSExecRole (then add whatever logins are
    required... check in the ReportServer or ReportServerTempDB databases if you're
    not sure)
    4. msdb > Security > Roles > RSExecRole (add the same
    logins you did to the master DB)
    In the end you need the same logins in
    RSExecRole role for the master, msdb, ReportServer, and ReportServerTempDB
    databases. ("ReportServer" is the default Reporting Services database name, in
    case that's not clear ;)

  • Threaded Sudoku solver - Assignment question (NOT LOOKING FOR ANSWERS  )

    Hi All,
    I'm going to be upfront and point out this is an assignment that i'm currently working on and i'm not receiving much in the way of feedback from the class forums.
    This is currently a 4th year OO assignment for UNSW Australia.
    What I am having trouble doing is figuring out where my program is deadlocking or dying. There have been a number of requirements set out by the assignment, basically no synchronization, no locking. We are able to use volatile, atomic, immutable and thread-local objects. The task is to find all solution for a given N x N sudoku problem using X number of threads. I have successfully built the solver (X = 0) without too much trouble and I thought i had managed to modify the recursive algorithm to suit but unfortunately I think I have come unstuck.
    Any generalized tips would be appreciated when implementing threads that utilise checking flags to determine when the thread is finished processing.
    Kind Regards,
    Chris Gibbs

    Honestly, I think that recursion (as you stated) would be the easiest way to have solved this problem. But as you stated, threads must be used to solve this problem as a requirement of the project...
    You could easily launch a Thread each time instead of calling your recursive method... that could possibly result in a crap load of threads, but the idea would work.
    Definitely take a look at the SwingWorker class here if you're able to use J2SE 6: [http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html|http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html]
    I currently use it while gathering data from several websites at the same time. What I did was create and execute() X number of MySwingWorker objects to collect the data, while they are not complete (i.e. MySwingWorker.isDone() is false) I just Thread.sleep(...).
    Give it a try. It may suit your needs.

  • How can I kill a thread.

    I have read the many threads about killing a thread but they dont answer the question I need to know.
    In class#1 I have the following snipet of code:
    for (int i=0; i < docs.size(); i++)
        try {
            boolean blncompleted = false;
         Map object = null;
            OntologyCreatorThread  ontThread = new OntologyCreatorThread ();
         ontThread.start();
         ontThread.join(15000); // Allow thread to process for up to 15 seconds.
         // If thread is still running, kill the thread.  I dont care about
         // clean up since its only using memory and cpu, no DB is ever touched.
         if (ontThread.getState().toString().equals("RUNNABLE")){
             ontThread.interrupt();
                ontThread.stop();
                // set flag to false
             blncompleted = false;
            else {
                // set flag to false and do a ton of other processing.
             blncompleted = false;
             object = ontThread.getObject();
        catch (Exception Ex){
            Ex.printStackTrace();
    In my thread I have the following:
    public class OntologyCreatorThread extends Thread {
        Map object = null;
        public OntologyCreatorThread(){
        public void run() {
           try {
             // The line below takes forever to run sometimes.
             object = functionCallToApi(stringOfText);
        public Map getObject() {
         return objects;
    If the thread takes to long to run I just want to kill it.
    I have tried interupt and stop and both dont work.  Inside the run method of the thread I call an external API
    which I pass a string of text.  I can not get into that code because its from a Off the shelf product that we dont
    have the code to.  If the call in the run method takes to long I want to just kill this thread in the main class(#1). 
    No matter what I do I cant get the damn thing to stop.
    The line below takes forever to run.
             object = functionCallToApi(stringOfText);
    Putting it in a while loop wont solve this problem because the processing is still taking place in the call to the api.
    Thanks in advanceMessage was edited by:
    Storm897

    Couple of things to consider:
    1. Note that Thread.interrupted() and t.isInterrupted() are very different methods. The former clears the interrupted status so that a subsequent call will return false. The latter does not affect the interrupt status on the thread.
    2. If your "atomic step one" catches an Exception, then you might be swallowing an InterruptedException. Basically the rule when a Thread is interrupted is that if it is in a blocking call, an InterruptedException is thrown. Otherwise, isInterrupted is set to true. So if you have blocking (I/O) calls in "atomic step one" and you're catching Exception, then it might be that the InterruptedException goes completely unnoticed.
    3. If "atomic step one" takes a long time and you really want to abort the thread instantly, then you need some kind of method for doing so--you need to program in safe "stopping points". For example:
    public class Helper implements Runnable {
       private boolean _continue = true;
       public void cancel() {
          _continue = false;
       public void run() {
          _continue = true;
          try {
             // Do something until in safe/stable state
             if(!_continue) return;
             // Do something until in safe/stable state
             if(!_continue) return;
             while(_continue) {
                 // process single record in large data set
                 // Safe to stop at the end of each loop
             if(!_continue) return;
             // Do something else . . . etc.
          } catch(InterruptedException ie) {
             _continue = false; // Unnecessary, but here for illustration
    }Casual programmers often don't care whether the thread stops safely or not, but it really is important especially if you are in the middle of some kind of transaction. That's why destroy(), cancel() et al are deprecated.

Maybe you are looking for

  • Adding line items in BAPI_PO_CHANGE

    Hi, i am using BAPI_PO_CHANGE and i have already created po line item under one PO. Now i want to add more line items under the same document number. How can i do that using BAPI_PO_CHANGE. Thanks

  • Portal db provider(best practice)

    Best practice question here. If I wanted to create a few db portlets(suggestions/questions) is there already an existing portal db provider/schema that I should add them to? Or is it best to simply create a schema and db provider?

  • Migrating current web site to Portal

    Where can I get information (hints, tips tricks) for migrating our current web services to Portal. We're running an Apache web server and have a lot of content created through FrontPage. We also have several services provided via Perl .cgi scripts. I

  • Bought iMac...can NOT load LR2 from disc.  Tried downloading LR5 from my  Adobe account...after 3 da

    Help loading LR5.  Am in Johannesburg SA.  Need to load LR5....tried loading from my Adobe account...after 3 days only minimal progress on download.  Cancelled.  Tried loading my LR2 disc to see if it would help the process.  Disc will not load.  Rec

  • Help needed about deleting files.

    Anyone could tell me what Java sentence can I use to delete a file from a UNIX filesystem. What class does provide this method?