SwingGUIs and Threads

Hello,
I have written a progressDialog. And now I am not sure if I did it the right way. It looks like it is working. But especially I would like to know if the way I did it could be problematic in terms of the Swing EventDispatching Thread and my Thread.
This is what I wanted to do:
A Task's (that is run as a thread) progress shall be watchable via a modal progressDialog. The updatefrequency of the content of the dialog shall configurable and triggered by a timer. Also the must be a function like decidetopopup (millisces).
This is how I did it:
A class that extends Thread named ProgressTask has two timers as members: a timer that triggers the popup and a timer that triggers the JProgressDialog.updatecontent() frequently. updatecontent changes the status of the progressbar, sets a new title for the dialog if needed, changes the icon that is displayed in that dialog and changes the text in that dialog.
So to sum it up:
in the actionperformed eventhandler (the listener is that thread itself) is the Jprogressdialog.show() done
in the same eventhandler is also the Jprogressdialog.updatecontent() done
in the run method of the thread is the actual work done (i.e. Reading a file) some variables are set frequently (when progress is done) that contain information about the icon/title/text/progressvalue for the progressdialog.
from the mainclass I do myProgressTask.start();

Hello,
I have written a progressDialog. And now I am not sure if I did it the right way. It looks like it is working. But especially I would like to know if the way I did it could be problematic in terms of the Swing EventDispatching Thread and my Thread.
This is what I wanted to do:
A Task's (that is run as a thread) progress shall be watchable via a modal progressDialog. The updatefrequency of the content of the dialog shall configurable and triggered by a timer. Also the must be a function like decidetopopup (millisces).
This is how I did it:
A class that extends Thread named ProgressTask has two timers as members: a timer that triggers the popup and a timer that triggers the JProgressDialog.updatecontent() frequently. updatecontent changes the status of the progressbar, sets a new title for the dialog if needed, changes the icon that is displayed in that dialog and changes the text in that dialog.
So to sum it up:
in the actionperformed eventhandler (the listener is that thread itself) is the Jprogressdialog.show() done
in the same eventhandler is also the Jprogressdialog.updatecontent() done
in the run method of the thread is the actual work done (i.e. Reading a file) some variables are set frequently (when progress is done) that contain information about the icon/title/text/progressvalue for the progressdialog.
from the mainclass I do myProgressTask.start();

Similar Messages

  • I have a problem in this that i want to paas a form in a case that when user pres n then it must go to a form but error arises and not working good and threading is not responding

    made in cosmos help please need it
    using System;
    using Cosmos.Compiler.Builder;
    using System.Threading;
    using System.Windows.Forms;
    namespace IUOS
        class Program
            #region Cosmos Builder logic
            // Most users wont touch this. This will call the Cosmos Build tool
            [STAThread]
            static void Main(string[] args)
                BuildUI.Run();
            #endregion
            // Main entry point of the kernel
            public static void Init()
                var xBoot = new Cosmos.Sys.Boot();
                xBoot.Execute();
                Console.ForegroundColor = ConsoleColor.DarkBlue;
                a:
                Console.WriteLine("------------------------------");
                Console.WriteLine("WELCOME TO THE NEWLY OS MADE BY THE STUDENTS OF IQRA UNIVERSITY!");
                Console.WriteLine("------------------------------");
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("\t _____                                
                Console.WriteLine("\t|     |        |            |        
    |            |      |");
                Console.WriteLine("\t|     |        |            |        
    |            |      |");
                Console.WriteLine("\t|     |        |            |        
    |            |      |");
                Console.WriteLine("\t|     |        |            |        
    |            |      |___________");
                Console.WriteLine("\t|     |        |            |        
    |            |                  |");
                Console.WriteLine("\t|     |        |            |        
    |            |                  |");
                Console.WriteLine("\t|     |        |            |        
    |            |                  |");
                Console.WriteLine("\t|     |        |            |        
    |            |                  |");
                Console.WriteLine("\t|     |        |            |        
    |            |                  |");
                Console.WriteLine("\t|_____|        |____________|         |____________|      ____________");
                string input;
                Console.WriteLine();
                Console.Write("\nAbout OS     : a");
                Console.Write("\nTo Shutdown  : s");
                Console.Write("\nTo Reboot    : r");
                Console.Write("\nStart Windows Normaly : n");
                Console.WriteLine();
                input = Console.ReadLine();
                if (input == "s" || input == "S"){
                    Cosmos.Sys.Deboot.ShutDown();
                else
                if (input == "r" || input == "R"){
                    Cosmos.Sys.Deboot.Reboot();
                else
                if (input == "a" || input == "A"){
                    Console.ForegroundColor = ConsoleColor.DarkBlue;
                    Console.Clear();
                    Console.WriteLine("\n\n\n-------------------------------------");
                    Console.WriteLine("version: DISPLAYS OS VERSION");
                    Console.WriteLine("about: DISPLAYS INFO ABOUT ANGRY OS");
                    Console.WriteLine("hello or hi: DISPLAYS A HELLO WORLD");
                    Console.WriteLine("MESSAGE THAT WAS USED TO TEST THIS OS!!");
                    Console.WriteLine("-----------------------------------");
                    Console.Write("You Want to know : ");
                    input = Console.ReadLine();
                    if (input == "version"){
                        Console.WriteLine("--------------------");
                        Console.WriteLine("OS VERSION 0.1");
                        Console.WriteLine("--------------------");
                    else
                    if (input == "about"){
                        Console.WriteLine("--------------------------------------------");
                        Console.WriteLine("OS IS DEVELOPED BY Qazi Jalil-ur-Rahman & Syed Akber Abbas Jafri");
                        Console.WriteLine("--------------------------------------------");
                    Console.Write("Want to go back to the main window");
                    Console.Write("\nYes : ");
                    string ans = Console.ReadLine();
                    if (ans == "y" || ans == "Y")
                        goto a;
                        Thread.Sleep(10000);
                    else
                    if (input == "n" || input == "N")
                        Thread.Sleep(5000);
                        Console.Clear();
                        for (int i = 0; i <= 0; i++){
                            Console.Write("\n\n\n\n\t\t\t\t\t  ____        ____   ___  
                            Console.Write("\n\t\t|\t\t |  |      |    |     
    |   |  | |  |  |");
                            Console.Write("\n\t\t|\t|    |  |----  |    |     
    |   |  | |  |  |---");
                            Console.Write("\n\t\t|____|____|  |____  |___ |____  |___|  |    |  |___");
                            Thread.Sleep(500);
                        Thread.Sleep(5000);
                        Console.Clear();
                        BootUserInterface();
                        Console.ReadLine();
    //                    Form1 fo = new Form1();
                    else{
                        for (int i = 0; i <= 5; i++){
                            Console.Beep();
                            Thread.Sleep(1000);
                            goto a;
                while (true);
            private static void BootUserInterface() {
                Thread t = new Thread(UserInterfaceThread);
                t.IsBackground = true;
                t.SetApartmentState(ApartmentState.STA);
                t.Start();
            private static void UserInterfaceThread(object arg) {
                Form1 frm = new Form1();  // use your own
                Application.Run(frm);
     

    Hi
    Jalil Cracker,
    >>when user pres n then it must go to a form but error arises and not working good and threading is not respondin
    Could you post the error information? And which line caused this error?
    If you want to show Form1, you can use form.show() method
    Form1 frm = new Form1();
    frm.Show();
    In addition, Cosmos is an acronym for C# Open Source Managed Operating System. This is not Microsoft product.If the issue is related to Cosmos, it would be out of our support. Thanks for your understanding. And you need raise an issue at Cosmos site.
    Best regards,
    kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Weblogic Enterprise 5.1 and threads

    I know when building servers based on WLE 4.2 in was a big no-no to link in threading libraries like pthread and thread. Is this still the case in Weblogic Enterprise 5.1?

    According to the product information, WLE 5.1 does not support Oracle 8.1.6, it
    only goes up to
    Oracle 8.1.5. But in general, I thought that with oracle there are 2 sets of
    libraries, one for threads and
    one for non-threaded support. You need to use the correct one, in the case of
    WLE, that would be the
    non-threaded one.
    MAS
    Paul Power wrote:
    Thanks Mary,
    Do you know of any customers who have managed to work
    with Oracle 8.1.6 without linking with the thread libraries ?
    cheers,
    P.
    Mary Ann Slavin wrote in message <[email protected]>...
    WLE 5.1 C++ is not a threaded product. Compiling WLE 5.1 C++ with thread
    libraries is not supported and will give unpredictable results for allprograms.
    This should not be done.
    Paul Power wrote:
    Hi Mary,
    Is it a dictate from BEA that you "can't" link with thread libraries ?
    We are using WLE 5.0.1 ( and some 5.1) with Oracle 8.1.6 on
    Solaris and found that we had to link using -lthread in order to use
    Oracle (not the case in 8.1.5)
    We don't actually attempt to try any threading in our apps and
    have not had any problems yet but if it's the case that there
    are known problems using threads we'd love to hear about
    them :-)
    As an aside, is Oracle 8.1.6 cleared for use by WLE ?
    P.
    Mary Ann Slavin wrote in message <[email protected]>...
    No matter how WLE 5.1 C++ is used, it cannot be compiled with threadedlibraries, so that restriction remains.
    A WLE C++ server can act as a client and call a WLE Java Server. Doingthis does not require the WLE C++ server to be compiled with threaded
    libraries.
    Wendell MacKenzie wrote:
    Does this also mean if CORBA C++ servers want to invoke threaded
    JavaServers
    the same DEFECT will be prevent this from being accomplished?
    Mary Ann Slavin wrote:
    WLE 5.1 does not have threads in the C++ clients or servers. Java
    threads are naturally occuring in the language, however, there are WLE
    restrictions on what can be done in the
    Java threads. These are documented.
    jd wrote:
    I know when building servers based on WLE 4.2 in was a big no-no
    to
    link in threading libraries like pthread and thread. Is this still thecase
    in Weblogic Enterprise 5.1?
    >

  • Implementing sockets and threads in a jframe gui program

    Hi, I am trying to find a solution to a problem I am having designing my instant messenger application.
    I am creating listening sockets and threads for each client logged into the system. i want to know if there is a way to listen to other clients request from the main gui and then if another client tries to establish a connection with me for example, a thread is created for that client and then my chat gui opens automatically has soon has the other client sends his or hers first text message to me.
    I am relatively new at socket programming has I am currently studying along this area. I know how to create threads and sockets but I am having trouble finding out a solution to my problem. Here is the code that I have done so far for the listening method from my main gui, and the thread class of what I have done so far.
    listening socket:
         private void listeningSocket()
                ServerSocket serverSocket = null;
                boolean listening = true;
                try
                    //listen in port 4444;
                    serverSocket = new ServerSocket(4444);
                catch(IOException x)
                    JOptionPane.showMessageDialog(null, "cannot listen to port 4444", null, JOptionPane.ERROR_MESSAGE);
                while(listening)
                    client_thread w;
                    try
                       w = new client_thread(serverSocket.accept(), jTextArea1);
                       Thread t = new Thread(w);
                       t.start();
                    catch(IOException x)
                         JOptionPane.showMessageDialog(null, "error, cannot start new thread", null, JOptionPane.ERROR_MESSAGE);
            }thread class:
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.event.*;
    * @author jonathan
    public class client_thread extends Thread
         //define new socket object
        private Socket client_user = null;
        private JTextArea textArea;
        public client_thread(Socket client_user, JTextArea textArea)
            this.client_user = client_user;
            this.textArea = textArea;
        public void run()
            BufferedReader in = null;
            PrintWriter out = null;
            String error = "error has occured, messege was not sent";
            String messege = null;
             try
                //create input and output streams
                in = new BufferedReader(new InputStreamReader (client_user.getInputStream()));
                out = new PrintWriter(client_user.getOutputStream(), true);
                while(true)
                   //read messege sent by user
                   messege = in.readLine();
                    //display messege in textfield
                   out.println(messege);
                   textArea.append(messege);
            catch (IOException e)
                //error messege
                JOptionPane.showMessageDialog(null, error, null, JOptionPane.ERROR_MESSAGE);
    }

    Seems like all you need to do is create a new dialog for each socket that is established. Your current design looks like it will attempt to use the same textarea for all the sockets.
    I would say in your thread class do the following:
    MyConversationDialog dialog = new MyConversationDialog();
    while(true)
                   //read messege sent by user
                   messege = in.readLine();
                    //display messege in textfield
                   out.println(messege);
                   dialog.setVisible (true);
                   dialog.addMessage (message);
                }

  • Documents and threads to start with Crystal reports with BI

    Hi,
    I am a BI consultant and searching for documents and threads to gain knowledge on Crystal reports .Could any one pls send me the pointers for the same...
    Kindly do the needful
    Points are assured.
    Thanks
    James

    You are in the right place for Crystal Reports and you may also want to look in the BI Forums.
    A good place to start is the Help file for Crystal Reports Designer and download our sample reports. They don't use B1 as the data source but it will help to see how to use CR.
    You need to specify specific questions and "how to's". Books have been written on how to use Crystal reports which is beyond the scope of this forum on one post.
    Thank you
    Don

  • MS 6.0 and Threads

    What is the official status of Measurement Studio 6.0 and Thread access? Right now all my DAQ stuff works great from Visual C++ 6.0 worker threads but my NiButton stuff doesn't. Is this expected? Do I still need to Post Messages to my NiButton controls in order to access them from within worker threads?
    Grant
    Grant M. Johnson
    Project Engineer
    LECO Corporation

    No, the User Interface controls should now support access from other threads. If you are seeing a problem, post the code or contact our tech support through http://www.ni.com/ask and we will see if we can give you an explanation.
    Best Regards,
    Chris Matthews
    National Instruments

  • User and thread feeds - wrong links in feed icon - Admins please check

    It seems (at least for me) that the user- and thread-specific feeds are broken. There are feed icons on user (for example: [https://forums.sdn.sap.com/profile.jspa?userID=3472354]) and thread (for example: [How to hide the columns in EVDRE]) pages. The tooltip for these icons indicate that it is a feed for the specific user or thread, but it actually just redirects to the main feed page where I can subscribe to individual forums.
    Am I doing something wrong here?
    Thanks!
    Ethan
    Edited by: Thomas Zloch on Oct 14, 2010 9:35 AM

    Hi David,
    No, that is incorrect. It is an issue with the SDN web page, not with the feeds or a feed reader. Try clicking on the little orange RSS icon at the bottom of this page. The page it redirects to is not an RSS feed - it is a web page that lists RSS feeds.
    For a long long time I thought that this was what was meant to happen. But I was really confused about why I couldn't find the feeds for threads or users, but the threads and users seemed to think that they had their own feeds. So I asked (a year ago).
    Then, more recently, I realized that the link at the bottom of the page was incorrect and if I re-jiggered it a little bit I could get to the actual RSS feed of the thread. Please take another look. Hopefully we can get this fixed!
    Thanks,
    Ethan

  • Understanding asynchronous BPEL processes and threading

    Hi everybody,
    I have a question regarding asynchronous BPEL processes and threading.
    I have an asynchronous BPEL process which delivers a message (picked up from a JMS topic) to a repository (via for instance an ICAN server). This transaction must be time-sensitive, i.e. first-in is first-out.
    If I have several threads running concurrently I have no guarantee that the messages are delivered in the same order that they where generated. It seems that the suggested way around this problem is to use single-threading.
    So here's the part that I do not understand:
    An asynchronous request does not wait for a response. If I use single-threading then what happens to that single-thread if for some reason (for instance the ICAN server is not responding) the BPEL instance is dehydrated? Is the thread still allocated for waiting for the first response or does it go back and pick up the next thing on the topic? If the next thing on the topic is picked up then how can I be sure that the messages are delivered in the correct order? If the thread is still allocated to the single instance then does that not kindda go against the whole concept of an asynchronous process?
    I hope some one can explain this to me.
    Thank you in advance.
    Kind regards,
    Mathias
    PS. This question is an attempt of a different angle on another forum thread: Asynchronuos BPEL - how to get the order of messages right?

    Hi again,
    A quick follow up question:
    Is there any way to have several BPEL processes running on the same server with different settings for how many threads to use?
    It seems that the only way to set number of threads used by BPEL is to use the configuration in the BPEL console? This is an domain setting - which means that all processes deployed to the server is effected the same way?
    I am asking because I am facing a scenario where I need one BPEL process to read from a AQ queue (well actually a topic) with a single thread and another BPEL process - deployed to the same BPEL server - to read from the same AQ queue with multiple threads.
    Does anyone have any idea of how to do this? Can it be done?
    Any suggestions, hints or reference to any documentation would be very much appreciated.
    Thank you in advance,
    Aagaard

  • Process and Thread

    I am new to the servlet and JSP technology.It is said that "Servlets and CGI differ mainly in Process and Thread.CGI used processes and Servlet technology uses Threads".I would like to know what exacly is the meaning of a process and a thread.How do we say that a process uses higher resources and hence a higher resource and memory overhead.
    What do we exactly mean by thread and how r they using less resources?When we say Thread t=new Thread(); what exactly is happening inside?

    A thread runs with in the context of the JVM process.
    http://java.sun.com/docs/books/tutorial/essential/threads/definition.html
    A process is the running of an executable. A cgi can be a C .exe file or a perl script run under perl.exe.
    The thread is faster because the jvm process has been loaded into memory and initialized. For each cgi call the operating system has to load the code into memeory and intialize all the variables and resources.
    http://c2.com/cgi/wiki?CgiVsServlet
    http://www.disc.com/jdbcserv.html

  • Process and threads

    Dear community
    Very kindly pleasant about information that is fiber in thread process and threads it interface between user and application ?
    is this answer on user ask in application run ?
    About any advises who concerns this matter , please .

    Hello RB_1.
    You can find more informations about fibers
    here and
    here on the MSDN Library.
    Bye.
    Luigi Bruno
    MCP, MCTS, MOS, MTA

  • Parallel function call and thread issue

    Sorry to post one issue here which is related to code. i was debugging a code which was wrote long time back by one developer. the issue is two function is called parallel using thread and one function set a variable true at end and another function just
    looping until the variable is set to true. the variable value is not getting set to true. here i am posting a code snippet and just tell me what is mistake in the code for which variable is not getting set to true by first function.
    when user click button then two function is invoked
    private void UPDATE_Click(object sender, System.EventArgs e)
    SavedFirst();
    AddCheckThread();
    public void SavedFirst()
    IsOpen = true;
    System.Threading.Thread loadT = new System.Threading.Thread(new System.Threading.ThreadStart(SaveAll));
    loadT.Start();
    IsOpen = false;
    private void AddCheckThread()
    if (!ALLFlag)
    loadingThread = new System.Threading.Thread(new System.Threading.ThreadStart(addCheck));
    loadingThread.Priority = System.Threading.ThreadPriority.Lowest;
    loadingThread.Start();
    private void SaveAll()
    if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate
    ALLFlag = false;
    if (!ALLFlag)
    loadingThread = new System.Threading.Thread(new System.Threading.ThreadStart(AddProducts));
    loadingThread.Priority = System.Threading.ThreadPriority.Lowest;
    loadingThread.Start();
    return;
    private void AddProducts()
    if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate
    ALLFlag = false;
    if (System.Windows.Forms.MessageBox.Show(this, "Would you like to add the details into the Database?", "Add?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
    if (comboOUR.SelectedItem == null || comboCountry.SelectedItem == null || comboSelleble.SelectedItem == null || txtOereff.Text == "" || txtUKPrice.Text == "" || txtUSPrice.Text == "" || txtSUrCharge.Text == "" || txtOURUS.Text == "" || txtOURUK.Text == "")
    FormValidation();
    else
    Gather_Data();
    bool isInserted = false;
    if (System.Windows.Forms.MessageBox.Show(this, "Would you like to add the details into \"Detailed-Product\" Too?", "Add?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
    isInserted = bbaProduct.BBASaveProduct();
    if (isInserted == true)
    isInserted = false;
    isInserted = bbaProduct.InsertInProductTable(BBAProduct.DetailProductID);
    if (isInserted == true)
    System.Windows.Forms.MessageBox.Show(this, "Product Successfully Added ", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Error Occurred !! Not Added Into the Database ", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Error Occurred !! Not Added Into the Database ", "Add");
    else
    isInserted = bbaProduct.InsertInProductTable(0);
    if (isInserted == true)
    System.Windows.Forms.MessageBox.Show(this, "Successfully Inserted Into the database", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Error Occurred !! Not Added Into the Database", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Process Cancelled By The User", "Add");
    ALLFlag = true;
    return;
    #region Add Check
    private void addCheck()
    if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate
    this.Opacity = 0.8;
    axShockwaveFlash1.Visible = true;
    axShockwaveFlash1.Play();
    while (!ALLFlag)
    int x = 0;
    axShockwaveFlash1.Visible = false;
    axShockwaveFlash1.Visible = false;
    axShockwaveFlash1.StopPlay();
    this.Opacity = 1;
    ALLFlag = false;
    loadingThread.Abort();
    return;
    help me to locate where is the mistake for which ALLFlag value is not getting set to true. thanks

    Your reliance on a field value across threads isn't going to work reliably.  In a multi-core/multi-threaded world the memory model allows for reading data out of order for optimization reasons.  Additionally the CPU can and will cache recently
    used data in memory that isn't shared across processors.  This can get you into trouble as you will not be reading the same value across processors.
    The only correct way to ensure that multiple threads access the same data correctly is to use sync objects that are designed for that such as a Semaphore or Mutex.  Sync objects allow you to safely share data across threads.
    Overall your code appears to be trying to update the UI using a thread but since it is calling Invoke each time you are basically spawning a thread that then blocks waiting for the UI thread.  You could pretty much eliminate your issues by getting rid
    of the threading calls altogether along with any sort of state management variables that were arbitrarily created (ALLflags) and simply use BeginInvoke.  You didn't post who was calling your higher level save methods but if it is a UI element then BeginInvoke
    and InvokeRequired are completely redundant as is all the threading.
    You can cleanly update this code to eliminate all the extra variables and threading and simply use the newer async/await functionality to help resolve the issues your code is having.  But you still have problems with the invoked code.  In one of
    the methods you are looping while waiting for a variable to be set.  But since you invoked it then it is occurring on the UI thread.  Because it is on the UI thread and that can only do 1 thing at a time, if ALLflag is false your code will deadlock. 
    The only other code that would set it to true cannot run because it is also invoked on the UI thread and only one of them can run at any one time.  Basically each of your threads are going to try to run on the same thread and only 1 of them will be able
    to.  Until the first thread method finishes the second one will never run.
    If you need Boolean flags then consider using a ManualResetEvent instead.  It is thread safe, works across threads and doesn't have any of the problems of a Boolean field when talking about threading. But you still have a deadlock between your invoked
    code that nothing will solve except rewriting your code.
    Michael Taylor
    http://blogs.msmvps.com/p3net

  • Find sequence and thread number of Oracle 10g Database

    Hallo!I am a newbie Oracle DBA studying for OCP.I am trying various methods of performing flashback of the database.
    Out of these options there is one that uses the sequence and thread numbers of the database as below
    RMAN> FLASHBACK DATABASE
    2> TO SEQUENCE=223 THREAD=1;
    How can I find out current sequence and thread numbers of the db to enable me implement such a flashback strategy?
    Thanks.

    Current sequence# is the one with status = CURRENT
    SELECT group#, thread#, sequence#, status FROM v$log;Lukasz

  • Are i++, i-- atomic and thread safe for int i

    I want to minimize the sync time multiple threads take to contend for a shared pool, which is implemented as a FIFO. My plan is to:
    1. Use a int variable "count" to trace the free obj count. Hence eliminates the need of synchonized methods size() and isEmpty()
    2. Increment & decrement count when implemeting push() and pop()
    3. Minimize the number of statements in synchonized block as possible within push() and pop(), which in this case, excludes count++ and count-- provided these operations are atomic and thread safe
    Have I lost something ?

    So, may I make a conclusion.
    To minimize contention, I use FIFO instead LIFO or stack and build it from scratch without extending from existing Collection-related class
    1 public class FIFO {
    2 . . private volatile int count;
    3 . . private Object head, tail;
    4 . . public Object pop() {
    5 . . . .synchonized (tail) {
    6 . . . . .if (count >= 3) {
    7 . . . . . .Object tail_origin = tail;
    8 . . . . . .// Re-organizing the linked list skipped
    9 . . . . . .synchonized (this) {
    10 . . . . . . count--;
    11 . . . . . }
    12 . . . . . return tail_origin;
    13 . . . . }
    14 . . . . else {
    15 . . . . . throw new PoolEmptyException();
    16 . . . . }
    17 . . . }
    18 . . }
    19 . . public void push(Object o) {
    20 . . . synchronized (head) {
    21 . . . . . // Re-organizing the linked list skipped
    22 . . . . . head = o;
    23 . . . . . synchonized (this) {
    24 . . . . . . count++;
    25 . . . . . }
    26 . . . }
    27 . . }
    28 . . public int sizeOf() {
    29 . . . return count;
    30 . . }
    31 }
    1. The reason I choose FIFO is to avoid the contention between push() and pop() -- they are NOT declared as synchonized, instead they only lock head and tail respectively. (Sorry I borrow the name push and pop from stack)
    2. pop() only works when count >= 3 to avoid head == tail after pop() and hence a further call to push() block concurrent call to pop() and vice versa (see line 5 and 20)
    3. The goal is to minimize the time and scope of contention. In line 9 and 23, I lock the whole pool object only when modify count, which is not atomic.
    4. This pool is used for a thread pool supporting many concurrent short-lived HTTP request
    Have I missed something ?
    Thanks a lot!

  • Static method and threads?

    I have a question regarding "static". for example, I have the following code
    class Test{
    public int i=0;
    public static calculateInt(){
    ....some operations on i;
    if two processes attempt to call Test.calculateInt() at the same time. What will the effects be? shall these two calls be implemented totally independent? each call holds it own "i" for calculation. OR there will be operation conflicit on i.
    what if I change "public i" to :private i", the same effects?

    You can't operate on i in a static method, since i is an instance variable.
    If you make i static, then you can operate on it in a static method. In that case, all threads will share a single i--there's only one i for the whole class, and threads don't change that. Making it private won't change that.
    If you make the method into an instance (non-static) method, then any threads operating on the same instance will share the same i, regardless of whether it's public or private. Different threads operating on different instances will each have their own i.
    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial
    Also check out http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html

  • Thread.suspend and Thread.resume

    I'm trying to build a class to replace the use of Thread.suspend() and Thread.resume() deprecated methods.
    I tried to as recommended on sun web page but it doesn't work : illegate state monitor exception.
    Does anyone have a solution ?
    Note :
    Source code
    package com.utils;
    public class SuspendableThread extends Thread {
         private Object mutex = new Object() ;
         private volatile boolean suspended = false ;
         private Runnable runnable ;
         public SuspendableThread ( Runnable runnable )
              super(runnable) ;
              this.runnable = runnable ;
         * Suspend the current thread
         public void doSuspend()
              synchronized (mutex) {
                   suspended = true ;
                   while(suspended) {
                        try {
                             runnable.wait() ;
                        } catch (InterruptedException e) {
                             e.printStackTrace();
         * Resume the current thread if suspended
         public void doResume()
              synchronized (mutex) {
                   if (suspended) {
                        suspended = false ;
                        runnable.notify() ;
    Exception
    java.lang.IllegalMonitorStateException: current thread not owner
         at java.lang.Object.wait(Native Method)
         at java.lang.Object.wait(Unknown Source)
         at com.utils.SuspendableThread.doSuspend(SuspendableThread.java:39)

    If you're synchronizing on the mutex, you should wait() and notify() on the mutex.
    synchronized (mutex) {
        suspended = true ;
        while(suspended) {
            try {
                mutex.wait(); //wait on the mutex
            } catch (InterruptedException e) {
                e.printStackTrace();
    synchronized (mutex) {
        if (suspended) {
           suspended = false ;
            mutex.notify(); //notify threads waiting on the mutex
    //...

Maybe you are looking for

  • My macbook keeps turning off and freezing on start up

    So like my macbook keeps either freezing on start up or it will just shut off or restart itself When it restarts itself it will bring up the main screen then this box comes up telling me to hold down the power button and restart it A friend said it m

  • How to read value of the period for which the sales volume has been entered

    Hi Experts, In the transaction "/ncrm_ipm_d_usage_data", we have a scenario where a user can enter value in the "sales volume reported" column for more than one period. Now we need to read the period_from (date from) for the first "sales volume repor

  • Attaching file in OWA not possible

    Since a while I cannot attach any file when working with Outlook web access application via Safari. It works with Firefox and was working in the past. Any suggestions? Thanks Nenad

  • R2 CU2 Software/Hardware Inventory updates taking very long to show up in the console after CU2 update

    I have recently updated my ConfigMgr 2012 R2 infrastructure from CU1 to CU2 prior to a large migration from 2007 R3. I ran a bunch of tests prior to the migration with the CU1 update and didn't notice any major issues with clients reporting in initia

  • Spain VAT ID

    Hi All, user is trying to give the VAT ID for a spain customer as ESJ41725920 and the sytem says the VAT registration number is invalid. When i check the same in T.Code Oy17, the length of the VAT registration number is 11 and checking rule is 3 and