Modifying the stack class to use multiple threads

Im trying to re write the stack class but with using 2 threads. One of the thread calls the pop method and the other calls the push method.
I don't know where im going wrong...
Any tips would be great thnx
Haven't bothered putting in any try / catch clauses yet, will make it look pretty later :)
http://nopaste.php-q.net/19555

java.util.Stack is thread safe so all you need to do are create two threads
one which pushes data onto the stack and one which pops it off.
class PushThread implements Runnable {
   private Stack stack;
   public PushThread(Stack s) {
      this.stack = s;
   public void run() {
     while(true) { // loop for ever
        stack.push(new Object());
        for(int i=0;i<100000;i++); // waste some time.
}The code above deliberatly does not use wait, sleep, notify etc as these
would force an ordering onto the stack. The code instead goes into a
loop that should waste time.
your PopThread class will be identical but will call stack.pop() instead.
matfud

Similar Messages

  • How to proces the record in Table with multiple threads using Pl/Sql & Java

    I have a table containing millions of records in it; and numbers of records also keep on increasing because of a high speed process populating this table.
    I want to process this table using multiple threads of java. But the condition is that each records should process only once by any of the thread. And after processing I need to delete that record from the table.
    Here is what I am thinking. I will put the code to process the records in PL/SQL procedure and call it by multiple threads of Java to make the processing concurrent.
    Java Thread.1 }
    Java Thread.2 }
    .....................} -------------> PL/SQL Procedure to process and delete Records ------> <<<Table >>>
    Java Thread.n }
    But the problem is how can I restrict a record not to pick by another thread while processing(So it should not processed multiple times) ?
    I am very much familiar with PL/SQL code. Only issue I am facing is How to fetch/process/delete the record only once.
    I can change the structure of table to add any new column if needed.
    Thanks in advance.
    Edited by: abhisheak123 on Aug 2, 2009 11:29 PM

    Check if you can use the bucket logic in your PLSQL code..
    By bucket I mean if you can make multiple buckets of your data to be processed so that each bucket contains the different rows and then call the PLSQL process in parallel.
    Lets say there is a column create_date and processed_flag in your table.
    Your PLSQL code should take 2 parameters start_date and end_date.
    Now if you want to process data say between 01-Jan to 06-Jan, a wrapper program should first create 6 buckets each of one day and then call PLSQL proc in parallel for these 6 different buckets.
    Regards
    Arun

  • Is there any problem to use multiple threads to send email with JavaMail

    Dear all,
    I am using JavaMail 1.3.2 to send emails with SMTP, it works very well for a long time.
    But one day, I found that the email service hanged and I could never send email again until I restart the tomcat. I found that the reason was a deadlock had been created, the required resource for sending email had not been released.
    I guess the error is due to multiple threads are sending email at the same time. I made a test to create seperate thread for sending each email. After few days, I found this deadlock happened again. So, my question is: Can I use JavaMail with multiple threads? If not, I may need to sychronized all the thread that using JavaMail. I would like to make sure this is the reason for causing the deadlock problem.
    Here is part of my code for using JavaMail:
    transport = session.getTransport("smtp");
    transport.connect(email_host, smtp_user, smtp_pass);
    message.saveChanges();
    transport.sendMessage(message,message.getAllRecipients());
    which is very standard call, and it worked well for a long time.
    Here is part for my thread dump on tomcat:
    (Thread-339)
    - waiting to lock <0x5447c180> (a sun.nio.cs.StandardCharsets)
    (Thread-342)
    - locked <0x5447c180> (a sun.nio.cs.StandardCharsets)
    It seems that these happened after call the method transport.sendMessage() or message.updateChanges()
    , and the underlying implementation may require the JRE StandardCharsets object. But the object had been locked and never be released. So, the sendMessage() or updateChanges() can't be completed.
    Please give me some helps if you have any idea about it.
    Thanks very much!
    Sirius

    Note that the Nightly build gets updated daily (and sometimes more than once in case of a respin) and it is always possible that something goes wrong and it doesn't work properly, so be prepared for issues if you decide to stay with the Nightly build and make sure to have the current release with its own profile installed as well in case of problems.
    See also:
    * http://kb.mozillazine.org/Testing_pre-release_versions
    *http://kb.mozillazine.org/Creating_a_new_Firefox_profile_on_Windows
    *http://kb.mozillazine.org/Shortcut_to_a_specific_profile
    *http://kb.mozillazine.org/Using_multiple_profiles_-_Firefox

  • Why need to restart server while modifying the servlet class

    Hi,
    i have some doubt, i hope any one can clear my doubt about servlet
    why we need to restart the web container while every time we modify the servlet class code
    Thanks & Regards
    vijay

    When you deploy a web application to a web container, you are deploying the
    .class files of your servlet not your source code. There is no servlet source code on the container (shouldn't be).
    So if you change your source code, the container knows nothing about it until you compile the code
    to create new .class files and then replace the container's class files with the new ones.
    You can configure most servers for hot deployment and/or start them in debug mode to ease the cycle during development.

  • How do i use multiple threads( very much real time), using JavaFX?

    I'm creating an application, using JavaFX because one can create awesome GUI using JavaFX. I need to know how to create real time multiple threads using javafx.
    JavaFX doesn't support creation of multiple threads, but i think there is another way of doing it. I need it work in real time as my application works with an hardware (wacom intous 3 tablet), and i need mutiple threads to get all the parameters from the stylus of the tablet simultaneously...
    any code which will help me out or explaination on how to go about this is appreciated...
    Help required quickly...

    See example at
    [http://jfxstudio.wordpress.com/2009/06/09/asynchronous-operations-in-javafx/|http://jfxstudio.wordpress.com/2009/06/09/asynchronous-operations-in-javafx/]

  • Client/Server in one program (using multiple threads)?

    Is there some examples out there of how to use a client and server in a single program using separate threads? Also, is it possible to start a third thread to control the packets, such as drop a random or specified number of packets (or match on specific data in a packet)?

    Just trying to have a client send udp packets to a server (all on the same machine running from the same program) and want to be able to drop packets coming from the client side to the server side.
    E.g.,
    Here's an example that I found here: http://compnet.epfl.ch/tps/tp5.html
    import java.io.<strong>;
    import java.net.</strong>;
    import java.util.<strong>;
    /</strong>
    * Server to process ping requests over UDP.
    public class PingServer {
         private static double lossRate = 0.3;
         private static int averageDelay = 100; // milliseconds
         private static int port;
         private static DatagramSocket socket;
         public static void main(String[] args) {
              // Get command line arguments.
              try {
                   if (args.length == 0) {
                        throw new Exception("Mandatory parameter missing");
                   port = Integer.parseInt(args[0]);
                   if (args.length > 1) {
                        lossRate = Double.parseDouble(args[1]);
                   if (args.length > 2) {
                        averageDelay = Integer.parseInt(args[2]);
              } catch (Exception e) {
                   System.out.println("UDP Ping Server");
                   System.out.println("Usage: java PingServer port [loss rate] [average delay in miliseconds]");
                   return;
              // Create random number generator for use in simulating
              // packet loss and network delay.
              Random random = new Random();
              // Create a datagram socket for receiving and sending UDP packets
              // through the port specified on the command line.
              try {
                   socket = new DatagramSocket(port);
                   System.out.println("UDP PingSever awaiting echo requests");
              } catch (SocketException e) {
                   System.out.println("Failed to create a socket");
                   System.out.println(e);
                   return;
              // Processing loop.
              while (true) {
                   // Create a datagram packet to hold incoming UDP packet.
                   DatagramPacket request = new DatagramPacket(new byte[1024], 1024);
                   // Block until the host receives a UDP packet.
                   try {
                        socket.receive(request);
                   } catch (IOException e) {
                        System.out.println("Error receiving from socket");
                        System.out.println(e);
                        break;
                   // Print the received data.
                   printData(request);
                   // Decide whether to reply, or simulate packet loss.
                   if (random.nextDouble() < lossRate) {
                        System.out.println("   Reply not sent.");
                        continue;
                   // Simulate network delay.
                   try {
                        Thread.sleep((int) (random.nextDouble() * 2 * averageDelay));
                   } catch (InterruptedException e) {}; // Ignore early awakenings.
                   // Send reply.
                   InetAddress clientHost = request.getAddress();
                   int clientPort = request.getPort();
                   byte[] buf = request.getData();
                   DatagramPacket reply = new DatagramPacket(buf, buf.length,
                             clientHost, clientPort);
                   try {
                        socket.send(reply);
                   } catch (IOException e) {
                        System.out.println("Error sending to a socket");
                        System.out.println(e);
                        break;
                   System.out.println("   Reply sent.");
          * Print ping data to the standard output stream.
         private static void printData(DatagramPacket request) {
              // Obtain references to the packet's array of bytes.
              byte[] buf = request.getData();
              // Wrap the bytes in a byte array input stream,
              // so that you can read the data as a stream of bytes.
              ByteArrayInputStream bais = new ByteArrayInputStream(buf);
              // Wrap the byte array output stream in an input stream reader,
              // so you can read the data as a stream of characters.
              InputStreamReader isr = new InputStreamReader(bais);
              // Wrap the input stream reader in a buffered reader,
              // so you can read the character data a line at a time.
              // (A line is a sequence of chars terminated by any combination of \r
              // and \n.)
              BufferedReader br = new BufferedReader(isr);
              // We will display the first line of the data.
              String line = "";
              try {
                   line = br.readLine();
              } catch (IOException e) {
              // Print host address and data received from it.
              System.out.println("Received echo request from "
                        + request.getAddress().getHostAddress() + ": " + line);
    }I'm looking to do the "processing loop" in a separate thread, but I'd also like to do the client in a separate thread
    So you're saying, just put the client code in a separate class and start the thread and that's it? As far as the packet rate loss thread, is this possible to do in another thread?

  • How to use multiple threads and swing for displaying status/interaction

    I have a Swing-app which have to show progress and allow userinteraction for these tasks:
    * First:
    retrieve a list of IDs(String) from the database (single thread running)
    * Second:
    some work on the id-list and list written to hd (same thread as above)
    * Third:
    retrieve Objects (based on the id-list) from different sources (Multiple Threads are running)
    To show the status I have a JProgressBar (indeterminate while task1&2 running) and
    a JTextArea showing the current status (connect,retrieve list, sort, ...)
    When task3 is starting the JTextArea have to disappear and be replaced by a ScrollPane
    with an array of Labels/TextAreas showing the status of each thread.
    While theses threads are working, the ID-list will be consumed and the JProgressBar
    shows the remaining precentage of the hole progress.
    Everything is working so far (excepts UI :) , the problem(s) I have:
    I need the threads to interacts with the user through the ui. e.g: "Connection to db-xyz lost! reconnect?"
    But I don&#180;t know how to do this correctly.
    I think one way would be to send an event to the ui... but how?
    (the ui must know which thread is calling to unpause it after user answered)
    I know that threads should NOT change the swing(-container) - How do I notify the ui that a thread has a question?
    Since these threads are really time-consuming the UI is not updated frequently,
    how can I increase this? (perhaps using another thread-priority?)
    thanks for help!

    if/when your threads need to interact with the UI, they can create a Runnable & send it to SwingUtilities.invokeLater or invokeAndWait. This Runnable can popup a message to the user, and act on the choice of the user (reconnect, cancel, ...). This action could be something which "unpauses" the task thread.
    You may need to do synchronisation between the code in the Runnable & the Thread to which it is related - so the latter Thread knows when the user has made the choice.

  • Is it possible to get the main class name in a Thread context ?

    for example, i want to get the main class name (the first entry of the program).
    public class Test implements Runnable {
         public Test() {}
         public static void main(String[] args) {
              new Thread(new Test()).start();
         public void run() {
              try {
                   //Want to get the main class name (not the current class name)
                   throw new Throwable();
              } catch (Throwable e) {
                   e.printStackTrace();
    }

    Acutally, i wanna make clear about the concept of a "Thread"
    Is it true that ..
    the main() method is a thread , once I create another thread in the program , both of (or all of them) will contains it owns stack exception information ?
    My english is poor, please try to understand it. Thx

  • Can i create more than one attributes for the custom class created using java API

    Hello everyone,
    I have been creating class and its attributes programatically using java APIs, I want to know that is there any way to create multipal attributs for the same class in just one call of API with all the options for each attributes,
    thanks

    You can create a new class and define all of the Attributes at the time the class is created - this is the preferred way of creating classes. Use the addAttributeDefinition() method on ClassObjectDefinition. If you need to add attributes to existing classes, you can only add them one at a time (using the addAttribute() method on ClassObject).
    (dave)

  • I can't modify the field MARC-LOSGR using the badi BADI_MATERIAL_REF

    Hello!
    I have to force a value in the field "lot size" (MARC-LOSGR) when the system extends automatically a material with the transaction CK40N.
    I tried to use the badi BADI_MATERIAL_REF, wich seems to be perfect for this purpose, but it doesn't work: after the badi the system resets the field to its initial value.
    What can I do?
    Thank you

    Dear Sauro
    I've found this thread in the forum, and because I've the same problem (I need to set 1000 as default for marc-losgr) during creation/extension of a material, I'd like know how you solved your issue.
    The BADI is called during CK11N and CK40N transaction, but even if I set the value in the right mode it's not saved on table MARC. Of course If I create manually the cost view by using MM01 the BADI works fine and the value is saved.
    Thank-you in advance for cooperation.
    Claudio
    Ps: se vuoi puoi anche rispondere direttamente in italiano al mio indirizzo che trovi nei miei riferimenti. Grazie

  • Setting The Enclosing Class Instance Using Reflection

    Hi,
    I'm implementing some customized deep clone mechanism.
    When I have an instance of an inner class (or anonymous inner class), I need to create a clone, that refer to a clone of the enclosing class (and not the original inner class).
    Any ideas if there's a way to implement this?
    for example
    class A implements IMyClonable
       class B implements IMyClonable
            public void cloneMe() {};
       public void cloneMe() {};
    }when cloning B instance b to bClone, the enclosing A instance of bClone, should be a clone of the enclosing A instance if b.
    Thanks,
    Roee

    s_roee wrote:
    Hi,
    I'm implementing some customized deep clone mechanism.
    When I have an instance of an inner class (or anonymous inner class), I need to create a clone, that refer to a clone of the enclosing class (and not the original inner class).
    Any ideas if there's a way to implement this?
    for example
    class A implements IMyClonable
    class B implements IMyClonable
    public void cloneMe() {};
    public void cloneMe() {};
    }when cloning B instance b to bClone, the enclosing A instance of bClone, should be a clone of the enclosing A instance if b.B.clone() retains the enclosing A instance.
    You could;
    write your A clone method
    define a copy constructor in B
    define a method in A that returns a copy of a B instance using the above B copy constructor
    have the B clone method create a clone of A and call the above copy method on this cloned instance of A.

  • How to modify the port number and use subdomains

    Couple of things ...
    1 - default port for installation is on 7777 and 7778. Would it be possible to run everything on port 80? I would like to hide the port number and not have people type in http://domain.com:7778
    2 - how can we use subdomains for certain services? For example, webmail should be http://webmail.domain.com and the RTC should be http://conference.biztech.com
    thx

    we're using OCS both inside and outside our network.
    I had my dba modify the port so now everything runs on port 80. However, I dont know how to get virtualhost to work correctly.
    conference.domain.com -> RTC piece
    webmail.domain.com -> webmail piece
    i.e....

  • Need help to Modify the STD report which uses the Tcode CATS_DA.

    Hi ,
    we have a requirement as below. we need Add two Additional Fileds in the OutPut of the Std Report ( Tcode CATS_DA) .( 2 fileds are  one is Managername /Manager employee number ) ..
    Can you Please where we need to Modify the code to meet the above requirement.
    Thanks in Advance.
    Edited by: sandeep on Jul 29, 2008 12:45 PM

    Copy the report to "Z" version and plug in fields .
    Thanks,
    Saquib

  • Finding the standard class name using methods

    hi experts,
                     How to find out the standard class if you have methods.for example i know a method name, so i want to know its class name.How to achieve that??

    Hi ,
    Go to transaction SE84. Repository Info system.
    CLASS LIBRARY -> METHODS .  Search as you like.

  • Using Multiple Threads

    I'm pretty new to Java and am currently working on this assignment for one of my classes:
    The goal is to create a program that will transfer an audio file using TCP/IP from a server to a client, then play the audio file. Additionally they wanted variable buffer sizes to measure the communication times when the buffer is changed. 've got all those parts complete (and good lord it took me days). The next step is to complete the same process, but begin playing the file before all the packets have been received by the client. That's where I'm stuck. Is a separate thread the way to go? If so, any suggestions on how to make that work would be appreciated.
    Currently I'm dumping all the data into a ByteArray once it's been received, but I'm suspecting this won't work for real time streaming. Am I right in thinking this, and if that's the case, are PipedOutputStreams the solution? (And if they are, how do I pass values like that between threads?)
    Below is the portion of code on the client side that works for transfer and play, but not for streaming.
    Thanks in advance for any assistance.
    <<<CODE>>>
    //Setup data repository and transfer data to the array
    byte[] byteData = new byte[byteCount];
    int t=0;
    double startTime = System.currentTimeMillis(); //Begin transfer time counter
    while(t!=byteCount){
    byteData[t]=inFromServer.readByte(); //Receive data
    t++;
    double endTime = System.currentTimeMillis() - startTime; //Calculate transfer time
    System.out.println("Total Delay Time: " + endTime/1000 + " seconds");
    //Stream the data into a byte array, set audio format, and setup the dataline
    ByteArrayInputStream arrayStream = new ByteArrayInputStream(byteData,0,byteCount);
    AudioInputStream audioStream = AudioSystem.getAudioInputStream(arrayStream);
    AudioFormat audioFormat = audioStream.getFormat();
    System.out.println("Now Playing: " + audioFormat);
    DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class,audioFormat);
    SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
    sourceDataLine.open(audioFormat);
    sourceDataLine.start();
    //Transfer data to the audio source dataline and play
    int counter;
    while((counter = audioStream.read(byteData,0,byteData.length)) != -1){
    if(counter >0)
    sourceDataLine.write(byteData,0,counter);
    sourceDataLine.drain();
    sourceDataLine.close();

    Well nix that I managed to have a breakthrough and got things working. =)
    Cheers!

Maybe you are looking for