Question about methods in a class that implements Runnable

I have a class that contains methods that are called by other classes. I wanted it to run in its own thread (to free up the SWT GUI thread because it appeared to be blocking the GUI thread). So, I had it implement Runnable, made a run method that just waits for the thread to be stopped:
while (StopTheThread == false)
try
Thread.sleep(10);
catch (InterruptedException e)
//System.out.println("here");
(the thread is started in the class constructor)
I assumed that the other methods in this class would be running in the thread and would thus not block when called, but it appears the SWT GUI thread is still blocked. Is my assumption wrong?

powerdroid wrote:
Oh, excellent. Thank you for this explanation. So, if the run method calls any other method in the class, those are run in the new thread, but any time a method is called from another class, it runs on the calling class' thread. Correct?Yes.
This will work fine, in that I can have the run method do all the necessary calling of the other methods, but how can I get return values back to the original (to know the results of the process run in the new thread)?Easy: use higher-level classes than thread. Specifically those found in java.util.concurrent:
public class MyCallable implements Callable<Foo> {
  public Foo call() {
    return SomeClass.doExpensiveCalculation();
ExecutorService executor = Executors.newFixedThreadPool();
Future<Foo> future = executor.submit(new MyCallable());
// do some other stuff
Foo result = future.get(); // get will wait until MyCallable is finished or return the value immediately when it is already done.

Similar Messages

  • Reflect the class that implements Runnable

    Hi,
    I am implementing the reflection of the class that implements Runnable. In order to start a new thread I am trying to invoke "start()" method ( which is obviously not defined my class ) and I therefore I am getting "java.lang.NoSuchMethodException".
    I am wondering is it possible at all to start a new thread on a reflected class?
    thanks in advance.
    {              Class refClass = Class.forName(className);
    String methodName = "start";
    Class[] types = new Class[1];
    types[0] = Class.forName("java.util.HashMap");
    Constructor cons = refClass.getConstructor(types);
    Object[] params = new Object[5];
    params[0] = new HashMap();
    Method libMethod = refClass.getMethod(methodName, null);
    libMethod.invoke(objType, null); }

    Well, if we knew what it meant to "start a thread on a class" we could probably figure out how to "start a thread on a reflected class". If we knew what a "reflected class" was, that is.
    In other words, it would help if you rephrased your question using standard terminology (and also explained why you want to do whatever it is you want to do).
    But let's guess for now: If you have an object which implements Runnable then you start a thread to run that object like this:
    Runnable r = // some object which implements Runnable
    new Thread(r).start();Not what you wanted? Go ahead and clarify then.

  • Serializing a class that implements the Singleton pattern

    Hello,
    I am relatively new to Java and especially to serialization so the answer to this question might be obvious, but I could not make it work event though I have read the documentation and the article "Using XML Encoder" that was linked from the documentation.
    I have a class that implements the singleton pattern. It's definition is as follows:
    public class JCOption implements Serializable {
      private int x = 1;
      private static JCOption option = new JCOption();
      private JCOption() {}
      public static JCOption getOption() { return option; }
      public int getX() { return x; }
      public void setX(int x) { this.x = x; }
      public static void main(String args[]) throws IOException {
        JCOption opt = JCOption.getOption();
        opt.setX(10);
        XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Test.xml")));
        encoder.setPersistenceDelegate(opt.getClass(),  new JCOptionPersistenceDelegate());
        encoder.writeObject(opt);
        encoder.close();
    }Since this class does not fully comply to the JavaBeans conventions by not having a public no-argument constructor, I have create a class JCOptionPersistenceDelegate that extends the PersistenceDelegate. The implementation of the instantiate method is as follows:
      protected Expression instantiate(Object oldInstance, Encoder out) {
           Expression expression = new Expression(oldInstance, oldInstance.getClass(), "getOption", new Object[]{});
            return expression;
      }The problem is that the resulting XML file only contains the following lines:
        <java version="1.5.0_06" class="java.beans.XMLDecoder">
            <object class="JCOption" property="option"/>
        </java> so there is no trace of the property x.
    Thank you in advance for your answers.

    How about this:
    import java.beans.DefaultPersistenceDelegate;
    import java.beans.Encoder;
    import java.beans.Expression;
    import java.beans.Statement;
    import java.beans.XMLEncoder;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    public class JCOption {
        private int x = 1;
        private static JCOption option = new JCOption();
        private JCOption() {}
        public static JCOption getOption() { return option; }
        public int getX() { return x; }
        public void setX(int x) { this.x = x; }
        public static void main(String args[]) throws IOException {
          JCOption opt = JCOption.getOption();
          opt.setX(10);
          ByteArrayOutputStream os = new ByteArrayOutputStream();
          XMLEncoder encoder = new XMLEncoder( os );
          encoder.setPersistenceDelegate( opt.getClass(), new JCOptionPersistenceDelegate() );
          encoder.writeObject(opt);
          encoder.close();
          System.out.println( os.toString() );
    class JCOptionPersistenceDelegate extends DefaultPersistenceDelegate {
        protected Expression instantiate(Object oldInstance, Encoder out) {
            return new Expression(
                    oldInstance,
                    oldInstance.getClass(),
                    "getOption",
                    new Object[]{} );
        protected void initialize( Class<?> type, Object oldInstance, Object newInstance, Encoder out ) {
            super.initialize( type, oldInstance, newInstance, out );
            JCOption q = (JCOption)oldInstance;
            out.writeStatement( new Statement( oldInstance, "setX", new Object[] { q.getX() } ) );
    }   Output:
    <?xml version="1.0" encoding="UTF-8"?>
    <java version="1.5.0_06" class="java.beans.XMLDecoder">
    <object class="JCOption" property="option">
      <void property="x">
       <int>10</int>
      </void>
    </object>
    </java>

  • Transform a class that implements JPanel into a bean.

    I'd to create a bean, from a class that implements JPanel, that in fact is a custom component.
    How can I create a bean?
    I have absolutely no idea about beans.
    What can make beans for me?
    I know a lot about the theory of ejb, is this what I need?
    I'm quite confused, please make me see the light!!!!!
    Thanks.

    Hi Daniel!
    To answer your question short as possible:
    Java -Beans are reusable code - components,
    similar to VB Active -X components,
    which you can use when developing your own
    applications.
    Beans can have a graphic user interface, so you
    can use builder tools like JBuilder or Beanbox
    to show them graphically in a designer.
    You can modify them about their properties,
    mostly shown in a special property window of a
    builder tool.
    It's really not very hard to create your own beans,
    the only thing you have to do is to pack all the
    classes which make the bean into a jar file.
    Then you can import the bean with the builder
    and it will be shown.
    The jar manifest file needs to look like for example:
    Manifest-Version: 1.0
    Name: BeanClock.class
    Java-Bean: True
    All the properties are implemented by public property-get
    and property-set methods, in order to show them in the property window.
    Java is doing that by introspection.
    Hope, this makes it a little bit clearer for you!

  • HELP?! a class that implements .....  : java.util.Vector

    My instructions say this:
    In the constructor, create the collection object (Since java.util.List is an interface, you will need to instantiate a class that implements this interface: java.util.Vector or java.util.LinkedList or java.util.ArrayList).
    I know, this IS a homework assignment - I am not sure how to go about this. I DO have code so far up to this point, can anyone help?
    import dLibrary.*;
    import java.awt.Color;
    * @author Rob
    * @version 8/18/03
    public class PhrasesII extends A3ButtonHandler
            private A3ButtonWindow win;
            private ATextField stringAcceptor;
            private ALabel listOstrings;
            private ALabel inputString;
            private ALabel status;
            private java.awt.List display;
            private java.util.List collection;
    public PhrasesII()
            win = new A3ButtonWindow(this);
            stringAcceptor= new ATextField (50,420,200,25);
            stringAcceptor.place(win);
            listOstrings = new ALabel(100, 10, 100, 380);
            listOstrings.setFontSize(10);
            listOstrings.setText("List of Strings:");
            listOstrings.place(win);
            inputString = new ALabel(50,400,200,25);
            inputString.setFontSize(10);
            inputString.setText("Input String:");
            inputString.place(win);
            display = new java.awt.List();
            display.setLocation(200, 100);
            display.setSize(200, 250);
            display.setBackground(Color.lightGray);
            win.add(display, 0);
            win.setLeftText("Save");
            win.setMidText("Display");
            win.setRightText("Discard");
            win.repaint();
      public void leftAction()
        public void midAction()
        public void rightAction()

    I am getting a " can't resolve symbol" when I do thisYou have to either import java.util.ArrayList or specify it fully, e.g., "new java.util.ArrayList()".
    Is that the line that is causing you problems? The error message should give the line number.
    my instructions also say I have to use "interface
    java.util.List when declaring your reference" so I am
    confused about using "= new ArrayList();"What they're saying is that you want code like this:
    private java.util.List frogs;    // this is the reference declaration
    //... later on...
    frogs = new java.util.ArrayList();  // this isn't a declarationWhat this means is that when you declare a field or variable, you should declare its type to be an interface.
    But when you actually instantiate a value for that variable, then you should use a concrete class that implements that interface. (You have to; interfaces can't be instantiated.)
    This is good programming style for reasons I don't have the space to explain here.

  • Performance wise which is best extends Thread Class or implement Runnable

    Hi,
    Which one is best performance wise extends Thread Class or implement Runnable interface ?
    Which are the major difference between them and which one is best in which case.

    Which one is best performance wise extends Thread Class or implement Runnable interface ?Which kind of performance? Do you worry about thread creation time, or about execution time?
    If the latter, then don't : there is no effect on the code being executed.
    If the former (thread creation), then browse the API Javadoc about Executor and ExecutorService , and the other execution-related classes in the same package, to know about the usage of the various threading/execution models.
    If you worry about, more generally, throughput (which would be a better concern), then it is not impacted by whether you have implemented your code in a Runnable implementation class, or a Thread subclass.
    Which are the major difference between them and which one is best in which case.Runnable is almost always better design-wise :
    - it will eventually be executed in a thread, but it leaves you the flexibility to choose which thread (the current one, another thread, another from a pool,...). In particular you should read about Executor and ExecutorService as mentioned above. In particular, if you happen to actually have a performance problem, you can change the thread creation code with little impact on the code being executed in the threads.
    - it is an interface, and leaves you free to extend another class. Especially useful for the Command pattern.
    Edited by: jduprez on May 16, 2011 2:08 PM

  • Modifying a Class that implements Serializable

    I have a class LDAPUser
    import java.io.*;
    public class LDAPUser implements java.io.Serializable{
         private java.lang.String name;
         private java.lang.String userID;
         private java.lang.String associateNumber;
    public LDAPUser() {
         super();
    public boolean equals(Object o) {
         if (o == this)
         return true;
         if (!(o instanceof LDAPUser))
         return false;
         return (((LDAPUser)o).getAssociateNumber().equals(this.getAssociateNumber()));
    public java.lang.String getAssociateNumber() {
         if(associateNumber == null){
              return getUserID();
         return associateNumber;
    public java.lang.String getName() {
         return name;
    public java.lang.String getUserID() {
         return userID;
    public void setAssociateNumber(java.lang.String newAssociateNumber) {
         associateNumber = newAssociateNumber;
    public void setName(java.lang.String newName) {
         name = newName;
    public void setUserID(java.lang.String newUserID) {
         userID = newUserID;
    It works fine.
    I needed to add functionality to it. These were the modifications.
    private java.lang.String distinguishedName;
    private boolean validUser;
    public java.lang.String getDistinguishedName() {
         return distinguishedName;
    public boolean isValidUser() {
         return validUser;
    public void setDistinguishedName(java.lang.String newDistinguishedName) {
         distinguishedName = newDistinguishedName;
    public void setValidUser(boolean newValidUser) {
         validUser = newValidUser;
    I am using visual age for java and in the Test environment the changes work fine.
    When I promote the changes to our application server (websphere) the changes are not there. I get a method not found error and though trial and error have identified that the server is not actually using the class from the jar. I have removed any other occurences of the class from the server.
    My question is if I change a Serializable class how do I make those changes take affect (thorough better coding) and for right now, where is this "old instance" of my class coming from and how do I get rid of it.
    Thanks in Advance,
    Jason Grieve

    If the server is running than the class might be already loaded through the class loader, so it wont be load again.
    this unless you use hot deployment, which you have to figure how it is being handled in your srver.
    Doron

  • Abstract Class that implements Comparable

    I am trying to understand how a comparable interface works with an abstract class. Any help is greatly appreciated.
    I have a class ClassA defined as follows:
    public abstract class ClassA implements Comparable I have a method, compareTo(..), within ClassA as follows:
    public int compareTo(Object o) I have a sub-class ClassB defined as follows:
    public class ClassB extends ClassAI am receiving a compile error:
    Class must implement the inherited abstract method packagename.ClassA.compareTo(Object)
    Should or can the compareTo be abstract in ClassA and executed in ClassB? Just not sure how this works.

    ???? if you are inheriting from an abstract class your subclass must implement methods that were declared in the parent (abstract) class but not implemented
    When in doubt, refer to the Java Language Specification..

  • Question about Methods

    I was wondering why i was not getting the right output. The program should give me..
    Storing : 0
    Checking Queue...
    Printing: 0
    Storing: 1
    Checking Queue...
    Printing:1
    etc...
    but instead all I get is...
    Storing :0
    Checking Queue..
    Storing:1
    Checking Queue...
    etc..
    Here is my Code:
    import java.util.ArrayList;
    public class Problem {
         public Storage storeMe = new Storage();
         public static void main(String[] args) {
              (new Thread(new Counter())).start();
              (new Thread(new Printer())).start();
    class Storage {
         ArrayList<Integer> queue = new ArrayList<Integer>();
         public int value;
         public int getValue() {
              if (queue.size() > 0)
                   return queue.remove(0);
              else
                   return -1;
         public void storeValue(int newvalue) {
              value = newvalue;
              queue.add(value);
    class Counter extends Problem implements Runnable {
         public void run() {
              int counter = 0;
              while (true) {
                   synchronized (this) {
                        try {
                             this.wait(1000L);
                        } catch (Exception e) {
                   System.out.println("Storing : " + counter );
                   storeMe.storeValue(counter);
                   counter++;
    class Printer extends Problem implements Runnable {
         public void run() {
              while (true) {
                   synchronized (this) {
                        try {
                             this.wait(1000L);
                        } catch (Exception e) {
                   System.out.println("Checking Queue ...");
                   int num = storeMe.getValue();
                   if (num != -1)
                        System.out.println("Printing : " + num);
    }I think the problem with my code is that in the Printer class, the storeMe.getValue() method is not updated. Or more accurately, the queue is not updated.
    Can anyone shed some light on this matter?
    thanks in advance..

    thanks for that info.
    this program worked fine using static variables and methods. But now I'm trying to do it without using static modifier with the exception of the main().
    I tried checking if there was an update on queue in the Printer class by changing the code to this:
    class Printer extends Problem implements Runnable {
         public void run() {
              while (true) {
                   synchronized (this) {
                        try {
                             this.wait(1000L);
                        } catch (Exception e) {
                   System.out.println("Checking Queue ...");
                   int num = storeMe.queue.size();
                        System.out.println("Queue size: " + num);
    }and I got this output:
    Storing : 0
    Checking Queue ...
    Queue size: 0
    Checking Queue ...
    Queue size: 0
    Storing : 1
    So basically, when the Printer Class runs and tries the to get the value from the storage class, it can't because the value read was 0, there was no queue. Does this mean that I have created a wrong object of the Storage class? or is there another way to call that method without using the static modifier?
    Specifically, How do I Try to call an instance of a method with its values still intact? Let's say I want My Printer Class to access the values inputted by the Counter Class in the Storage Class.

  • A question about non-static inner class...

    hello everybody. i have a question about the non-static inner class. following is a block of codes:
    i can declare and have a handle of a non-static inner class, like this : Inner0.HaveValue hv = inn.getHandle( 100 );
    but why cannot i create an object of that non-static inner class by calling its constructor? like this : Inner0.HaveValue hv = Inner0.HaveValue( 100 );
    is it true that "you can never CREATE an object of a non-static inner class( an object of Inner0.HaveValue ) without an object of the outer class( an object of Inner0 )"??
    does the object "hv" in this program belong to the object of its outer class( that is : "inn" )? if "inn" is destroyed by the gc, can "hv" continue to exist?
    thanks a lot. I am a foreigner and my english is not very pure. I hope that i have expressed my idea clearly.
    // -------------- the codes -------------------
    import java.util.*;
    public class Inner0 {
    // definition of an inner class HaveValue...
    private class HaveValue {
    private int itsVal;
    public int getValue() {
    return itsVal;
    public HaveValue( int i ) {
    itsVal = i;
    // create an object of the inner class by calling this function ...
    public HaveValue getHandle( int i ) {
    return new HaveValue( i );
    public static void main( String[] args ) {
    Inner0 inn = new Inner0();
    Inner0.HaveValue hv = inn.getHandle( 100 );
    System.out.println( "i can create an inner class object." );
    System.out.println( "i can also get its value : " + hv.getValue() );
    return;
    // -------------- end of the codes --------------

    when you want to create an object of a non-static inner class, you have to have a reference of the enclosing class.
    You can create an instance of the inner class as:
    outer.inner oi = new outer().new inner();

  • Importing classes that implement jsp tags

              I was making a custom JSP tag library. The tag functionality was implemented in
              a class called, lets cay ClassA. I made the tld file and put it under the WEB-INF
              directory. The class which implemented the functionality was placed under WEB-INF/classes
              directory. I had the imported the tag library using the taglib directive. I was
              getting an error which said "cannot resolve symbol". But when I in the JSP file
              I imported the class file which implemented the taglib functionality the error
              vanished. Is it necessary to import the class files even if the taglib is imported.
              The documentation does not say so. Or is there some configuration I have to make.
              

    I think was a side effect of the .jsp changing redeploys the web app in 6.0.
              When the web app was redeployed your directory structure was reread and thus
              it found your .tld.
              Sam
              "bbaby" <[email protected]> wrote in message
              news:3b422db7$[email protected]..
              >
              > I was making a custom JSP tag library. The tag functionality was
              implemented in
              > a class called, lets cay ClassA. I made the tld file and put it under the
              WEB-INF
              > directory. The class which implemented the functionality was placed under
              WEB-INF/classes
              > directory. I had the imported the tag library using the taglib directive.
              I was
              > getting an error which said "cannot resolve symbol". But when I in the JSP
              file
              > I imported the class file which implemented the taglib functionality the
              error
              > vanished. Is it necessary to import the class files even if the taglib is
              imported.
              > The documentation does not say so. Or is there some configuration I have
              to make.
              >
              >
              

  • How can I know a class which implements Runnable interface has terminated?

    Hello! I have a class which has implements Runnable interface, while I want to execute some operation when the thread has terminate in multithread enviroment.How can I know the thread has terminated?Does it give out some signal?Cant I just call my operation at the end of the run() method?

    I want to execute some operation when
    the thread has terminate in multithread enviroment....
    Cant I just call my operation at the end
    of the run() method?Sure. Before run() ends, invoke that other operation.
    How
    can I know the thread has terminated?Does it give out
    some signal?Not that I'm aware of, but you can do what you described above, or I believe a different object can call isAlive on the thread.

  • Question about view/controller/nib class design

    Assume you need to make an application with, let's say, 15 different views in total. There are two extreme design choices you can use to implement the app:
    1) Every single view has its own view controller and a nib file. Thus you end up with 15 controller classes and 15 nib files (and possibly a bunch of view classes if any of your views needs to be somehow specialized).
    2) You have only one controller which manages all the views, and one nib file from which they are loaded.
    AFAIK Apple and many books recommend going purely with option #1. However, going with this often results in needless complexity, large amounts of classes (and nib files) to be managed and complicated class dependencies, especially if some of the views (and thus their controllers) interact with each other or share something (something which would be greatly simplified if all these related views were handled by one single controller class).
    Option #2 also usually ends up being very complex. The major problem is that the single controller will often end up being enormous, handling tons of different (and usually unrelated) things (which is just outright bad design). This is seldom a good design, unless your application consists of only a few views which are closely related to each other (and thus it makes sense for one single controller class to handle them).
    (Option #2 also breaks the strictest interpretation of the MVC pattern, but that's not really something I'm concerned about. I'm concerned about simple design, not about following a programming pattern to the letter.)
    A design somewhere in between the two extremes often seems to be the best approach. However, since I don't have decades of Cocoa programming experience, I would like to hear some opinions about this subject matter from people with more experience on that subject. (I do have object-oriented programming experience, but I have only relatively recently started programming for the iPhone and thus Cocoa and its design patterns are relatively new to me, so I'm still learning.)

    Somehow I get the feeling that my question was slightly misunderstood.
    I was not asking "which one of these two designs do you think is better, option #1 or option #2?" I already said in my original post that option #2 is bad design (unless your application consists of just one or two views). That's not the issue.
    The issue is that from my own experience trying to adhere very strictly to the "every single view must have its own view controller and nib file" often results in needless complexity. Of course this is not always the case, but sometimes you end up having controller classes which perform very similar, if not even the exact same actions, resulting in code repetition. (An OO'ish solution to this problem would be to have a common base class for these view controllers where the common functionality has been grouped, but this often just adds to the overall complexity of the class hierarchy rather than alleviating it.)
    As an example, let's assume that you have a set of help screens (for example one help screen for each major feature of the app) and a view where you can select which help view to show. Every one of these views has, for example, a button to immediately exit the help system. If you had one single controller class managing these views, this becomes simpler: The controller can switch between any of the views and the buttons of each view (most of them doing the same things) can call back actions on this controller (eg. to return to the help selection or to exit the help screen completely). These help screens don't necessarily have any functionality of their own, so it's questionable what do they would need view controllers of their own. These view controllers would basically be empty because there's nothing special for them to do.
    View controllers might make it easy to use the navigation controller class, but the navigation controller is suitable mainly for utility apps but often not for things like games. (And if you need animated transitions between views, that can be implemented using the UIView animation features.)
    I also have hard time seeing the advantages of adhering strictly to the MVC pattern. The MVC pattern is useful in things like web servers, where MVC adds flexibility. The controller acts as a mediator between the database and the user interface, and it does so in such an abstract way that either one can be easily changed (eg. the "view", which normally outputs HTML, could be easily changed to a different "view" which outputs a PDF or even plain text, all this without having to touch the controller or the model at all). However, I'm not seeing the advantages of the MVC pattern in an iPhone app. It provides a type of class design, but why is it better than some other class design? It's not like the input and output formats of the app need to be changed on the fly (which is one advantage of a well-designed program using the MVC pattern).

  • Calls to methods in a class that extends Thread

    Hello,
    I have some code that I am initiating from within an ActionListener that is part of my programs GUI. The code is quite long winded, at least in terms of how long it takes to perform. The code runs nicely, however once it is running the GUI freezes completely until operations have completed. This is unacceptable as the code can take up to hours to complete. After posting a message on this forum in regard to the freezing of the GUI it was kindly suggested that I use multi-threading to avoid the unwelcome program behaviour.
    The code to my class is as follows:
    public class FullURLAddress
      private boolean success_flag = true;
      private BufferedReader iN;
      private Document dT;
      private EditorKit kT;
      private Element lmNt;
      private ElementIterator lmIterate;
      private XURL[] compAddress;
      private int countX = 0;           //Tracks Vector vT's size.
      private int countY = 0;           //Tracks Vector vS's size.
      private int xURLcount = 0;        //Tracks XURL objects instantiated by this FullURLAddress object.
      private SimpleAttributeSet simpAtSet;
      private String aURL;              //Contains original (Xtended) URL!
      private String fileType;
      private String indexContent;
      private String[] parseURL;
      private String[] finalStrings;
      private String[] sortStrings;
      private URL indexConnect;
      private URLConnection iconn;
      private Vector vT;            //Stores href information, from targeted URL's HTML souce code.
      private Vector vS;            //Stores sorted HREF info ".jpg" and ".gif" only (no: png, tiff, etc).
      public FullURLAddress(String aURL)
        this.aURL = aURL;
        try{
          indexConnect = new URL(aURL);
          iconn = indexConnect.openConnection();
          iN = new BufferedReader(new InputStreamReader(iconn.getInputStream()));
            /* Document creation, analysis objects instantiated */
          vT = new Vector();
          vS = new Vector();
          kT = new HTMLEditorKit();
          dT = kT.createDefaultDocument();
          dT.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            /* Iterate through document and store all HREF values */
          kT.read(iN, dT, 0);
          lmIterate = new ElementIterator(dT);
          while((lmNt = lmIterate.next()) != null)
            simpAtSet = (SimpleAttributeSet)lmNt.getAttributes().getAttribute(HTML.Tag.A);
            if(simpAtSet != null)         //As long as there are A tags to be read...
              vT.addElement(simpAtSet.getAttribute(HTML.Attribute.HREF));
              countX++;//Tracks number of HREF occurences occur, giving better control of the Vector.
        }catch(MalformedURLException e){
          success_flag = false;
          System.out.println("FullURLAddress object has encountered a "+
                             "MalformedURLException at: "+aURL);
        }catch(IOException e){
          e.getMessage();
          success_flag = false;
        }catch(BadLocationException e){
          e.getMessage();
          success_flag = false;
        /* Searches through all HREF attributes that are now stored in Vector
           vT for occurences of the character string ".htm" */
        sortStrings = new String[countX];
        for(int i=0;i<countX;i++)
          sortStrings[i] = (String)vT.elementAt(i); //Vector Strings transfered into array.
          if(sortStrings.endsWith("gif")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("GIF"))
    vS.addElement(sortStrings[i]);
    countY++;
    if(sortStrings[i].endsWith("jpg")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("JPG"))
    vS.addElement(sortStrings[i]);
    countY++;
    finalStrings = new String[countY];
    for(int j=0;j<countY;j++)
    finalStrings[j] = (String)vS.elementAt(j);
    public int getCount()
    return countY; //Returns number of instances of htm strings
    } //ending with either "jpg" or "gif".
    public String[] xurlAddressDetails()
    return finalStrings;
    I have changed the above code to make use of multithreading by making this class extend Thread and implementing the run() method as follows:
    public class FullURLAddress extends Thread
      private boolean success_flag = true;
      private BufferedReader iN;
      private Document dT;
      private EditorKit kT;
      private Element lmNt;
      private ElementIterator lmIterate;
      private XURL[] compAddress;
      private int countX = 0;           //Tracks Vector vT's size.
      private int countY = 0;           //Tracks Vector vS's size.
      private int xURLcount = 0;        //Tracks XURL objects instantiated by this FullURLAddress object.
      private SimpleAttributeSet simpAtSet;
      private String aURL;              //Contains original (Xtended) URL!
      private String fileType;
      private String indexContent;
      private String[] parseURL;
      private String[] finalStrings;
      private String[] sortStrings;
      private URL indexConnect;
      private URLConnection iconn;
      private Vector vT;            //Stores href information, from targeted URL's HTML souce code.
      private Vector vS;            //Stores sorted HREF info ".jpg" and ".gif" only (no: png, tiff, etc).
      public FullURLAddress(String aURL)
        this.aURL = aURL;
      public void run()
        try{
          indexConnect = new URL(aURL);
          iconn = indexConnect.openConnection();
          iN = new BufferedReader(new InputStreamReader(iconn.getInputStream()));
            /* Document creation, analysis objects instantiated */
          vT = new Vector();
          vS = new Vector();
          kT = new HTMLEditorKit();
          dT = kT.createDefaultDocument();
          dT.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            /* Iterate through document and store all HREF values */
          kT.read(iN, dT, 0);
          lmIterate = new ElementIterator(dT);
          while((lmNt = lmIterate.next()) != null)
            simpAtSet = (SimpleAttributeSet)lmNt.getAttributes().getAttribute(HTML.Tag.A);
            if(simpAtSet != null)         //As long as there are A tags to be read...
              vT.addElement(simpAtSet.getAttribute(HTML.Attribute.HREF));
              countX++;//Tracks number of HREF occurences occur, giving better control of the Vector.
        }catch(MalformedURLException e){
          success_flag = false;
          System.out.println("FullURLAddress object has encountered a "+
                             "MalformedURLException at: "+aURL);
        }catch(IOException e){
          e.getMessage();
          success_flag = false;
        }catch(BadLocationException e){
          e.getMessage();
          success_flag = false;
        /* Searches through all HREF attributes that are now stored in Vector
           vT for occurences of the character string ".htm" */
        sortStrings = new String[countX];
        for(int i=0;i<countX;i++)
          sortStrings[i] = (String)vT.elementAt(i); //Vector Strings transfered into array.
          if(sortStrings.endsWith("gif")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("GIF"))
    vS.addElement(sortStrings[i]);
    countY++;
    if(sortStrings[i].endsWith("jpg")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("JPG"))
    vS.addElement(sortStrings[i]);
    countY++;
    finalStrings = new String[countY];
    for(int j=0;j<countY;j++)
    finalStrings[j] = (String)vS.elementAt(j);
    /* What happens with these methods, will they need to have their
    own treads also? */
    public int getCount()
    return countY; //Returns number of instances of htm strings
    } //ending with either "jpg" or "gif".
    public String[] xurlAddressDetails()
    return finalStrings;
    Are there any special things that I need to do in regard to the variables returned by the getCount() and xurlAddressDetails() methods. These methods are called by the code that started the run method from within my GUI. I don't understand which thread these methods are running in, obviously there is an AWT thread for my GUI and then a seperate thread for my FullURLAddress objects, but does this new thread also encompass the getCount() and xurlAddressDetails() methods?
    Please explain.
    This probably sounds a little wack, but I don't understand what thread is responisble for the methods in my FullURLAddress class aside of course from the run() method which is obvious. Any help will be awesome.
    Thanks
    Davo

    Threads are part of code that allows you to run multiple operations "simultaneously". "Simultaneously", because threads are not run actually simultaneously in any one-CPU machine. Since you most propably have only one CPU in your system, you can only execute one CPU instruction at time. Basically this means that your CPU can handle only one java-operation at time. It does not matter if you put some code in thread and start it, it will still take up all CPU time as long as the thread runs.
    So you would need a way to let other threads run also, for that purpose thread contains a yield feature that allows you to give time for other threads to run.
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Thread.html#yield()
    You need to use thread's yield() method in your thread code, in a place you want to give other threads time to run. Also bear in mind that if you yield your first thread run to allow second thread to run, you also need to add yield to the second thread also. If you don't, after yielding the first thread, the second thread will eat up all CPU time until it finishes, thus meaning the rest of your first thread will be run after second thread is done.
    One good place to execute yield() is usually at the end of a loop, for example 'for' or 'while' loop. This way you prevent for example while-deadlocks.
    Here is a java thread tutorial, worthy reading:
    http://java.sun.com/docs/books/tutorial/essential/threads/

  • Adding data members and methods to generated classes that will not produce

    I want to use XMLBeans XMLObject for a project, but for the classes generated by XMLBeans, I want to add some additional data members and methods to handle program state that I do not want to have written out to an XML document.
    I have been using .NET's system.xml.XmlParser class, and it provides this sort of capability.
    In looking at the code produced by XMLObject, it looks possible.
    Question: Does anyone have any thoughts on the best way to accomplish what I want to do? Is there a good design pattern to follow?
    Question: Are there any gotchas in doing this? The only immediate one I can think of is that everytime the .java files are regenerated by XMLObject, I will have to reinsert my data members and methods.

    Hi Chuck,
    Setting the dispaly Field property should in no way affect your validation execution.
    The valiadtion if is working fine on the field value when it is not a display field it should do so when a display field as well.
    Besides if you are working on MDM main table all the main table fields are display fields.even if you do not set the property.As main table fields are always visible in MDM Data manager.
    Which version of MDM you are currently working on.
    As I have tried on the SP06 version on MDM and the  Null  validation runs fine on Display fields as well.
    Check your MDM version and also your MDM clients as well as MDM server be on the same version.
    What I am finding confusing here is that initially you wish to keep the material number as Blank for the approver to enter the material number which will be send through a mail.
    But the validation is checking for the material field to be balnk then how are you poulating the same field with Material number in the later stage.As it will fail the validation here.As per teh vlaidation it should remain blank as soon as someone enters a value it will throw an error.
    Or in either which wise you need to mainatin 2 valiadtion steps before and after the Approver for blank and filled field check.
    Just check your process flow correctly and the order of it in case that is causing the records to fail.
    Hope It Helped
    Thanks & Regards
    Simona Pinto

Maybe you are looking for

  • T61 with memory leak on XP for driver battc.sys

    Hi I have an issue with XP where the battc.sys module that is part of Windows XP and responsible for the kernel side of monitoring the battery status. This module continually leaks memory until I have no more kernel paged resources left and programs

  • Sharing one library on external NAS drive for multiple users on one ibook

    Hi there, We (my wife and I) have only the ibook. We would like to use only 1 iphoto library for all of our family photos. I have a network drive with a bigger capacity to store the library. I read the post by CaptSwing. It seem to easier if library

  • Index oput of range 12348

    hI, While creating external datasource i am getting error string index oput of range 12348 thanks

  • Data Transfer Erec and ECC HR

    Hi all, We are using having 2 backend systems 1 for HR other than Erec and another one for erec. Now we have setup the ALE data transfer using Message type HRMD_ABA. In erec we have only ERECRUIT Component deployed in backend,no EA HR or SAP HR compo

  • How to Link Sales Order for Non Purchase items to Purchase Order

    Hi, I am using SAP 2007A SP01 PL05. I am creating a Sales Order for Non Purchase Items where i have 3 companies involved. 1. Owner of the Product 2. Transport Agent 3. Customer Owner Sells to the Customer non Purchase Items manufactured internally. O