Atomic block of code in SwingWorker thread?

Hi,
I am coding a Swing application. It has a SwingWorker thread that can be interrupted by a Progress bar.
Inside the worker thread, there are a few lines of code (not a method) that should be executed all or none. In another word,
if the thread runs in the middle of this block, the thread must finish this block. How can this be accomplished? This block of code has nothing to do with database read/write. The reason for the block of code being atomic is that I need to make sure of data consistency. There are no other thread except for
the main thread(event-dispatch thread) and the worker thread.
Thanks a lot!
David

You need to synchronize your atomic block and the code to interrupt the thread on the same object.

Similar Messages

  • Is SwingWorker Thread Cancellation Cooperative?

    Hello,
    Would appreciate any help in understanding this.  My understanding is that cancellation of a SwingWorker thread is cooperative.  However, that isn't what I'm seeing. 
    I have code below that will stop the SwingWorker thread even though I have no operations that are interruptable.  Note for the test that I have specifically put an infinite loop in doStuff().   When I do the cancellation in the main() routine: worker.cancel(true), I end up in the done() function indicating that doInBackground() exited.  It looks like the thread is being killed even in the absence of an interruptable operation.  Note if I change to worker.cancel(false), I get the same effect.  
    class AWorker extends SwingWorker<String, Object> {
      void doStuff() {'
    System.out.println("Entered doStuff");   
        while (true);
      @Override
      public String doInBackground() {
        //System.out.println("doInBackground started");
        doStuff();
        return "hello";
      @Override
      protected void done() {
        try {
          System.out.println("done() entered");
          String status = get();
          System.out.println("done(): get = " + status);
        } catch (Exception e) {
          System.out.println("done(): Exception: " + e);
    public class InterruptThread {
      public static void main(String[] args) throws Exception {
        AWorker worker = new AWorker();
        worker.execute();
        Thread.sleep(5000);
        worker.cancel(true);

    Hello,
    Would appreciate any help in understanding this.  My understanding is that cancellation of a SwingWorker thread is cooperative.  However, that isn't what I'm seeing. 
    I have code below that will stop the SwingWorker thread even though I have no operations that are interruptable.  Note for the test that I have specifically put an infinite loop in doStuff().   When I do the cancellation in the main() routine: worker.cancel(true), I end up in the done() function indicating that doInBackground() exited.  It looks like the thread is being killed even in the absence of an interruptable operation.  Note if I change to worker.cancel(false), I get the same effect.  
    class AWorker extends SwingWorker<String, Object> {
      void doStuff() {'
    System.out.println("Entered doStuff");   
        while (true);
      @Override
      public String doInBackground() {
        //System.out.println("doInBackground started");
        doStuff();
        return "hello";
      @Override
      protected void done() {
        try {
          System.out.println("done() entered");
          String status = get();
          System.out.println("done(): get = " + status);
        } catch (Exception e) {
          System.out.println("done(): Exception: " + e);
    public class InterruptThread {
      public static void main(String[] args) throws Exception {
        AWorker worker = new AWorker();
        worker.execute();
        Thread.sleep(5000);
        worker.cancel(true);

  • [Problem reading a file in a static block of code]

    Hi all,
    I'm trying to use a static block of code in an abstract class (let's say for initialisation). In this block I'm trying to read some lines of text from a file, and some FileNotFoundException are thrown,
    java.io.FileNotFoundException: file:/home/tom/workspace/cryptanalysis/data/keys (No such file or directory)
    java.io.FileNotFoundException: file:/home/tom/workspace/cryptanalysis/data/french_words (No such file or directory)
    but all the paths are valid and the files exist as you can see:
    tom@javahouse ~ $ ll /home/tom/workspace/cryptanalysis/data/
    total 24K
    -rw-r--r-- 1 tom users 151 jan 3 23:26 french_frequences
    -rw-r--r-- 1 tom users 2,0K jan 4 17:21 french_texts
    -rw-r--r-- 1 tom users 11K jan 4 17:16 french_words
    -rw-r--r-- 1 tom users 159 jan 4 17:21 keys
    tom@javahouse ~ $ cat /home/tom/workspace/cryptanalysis/data/french_words
    LE
    DE
    UN
    ETRE
    ET
    A
    IL
    AVOIR
    NE
    JE
    SON
    QUE
    SE
    QUI
    CE
    DANS
    I really don't understand why those exceptions are thrown, if somebody
    could help it would be very nice. (It is for a crypto school project)
    Thanks in advance. (Sorry for my english 'cause I'm french)
    Here is a code snippet :
    // Path to this class:
    // /home/tom/workspace/cryptanalysis/utils/TextUtils.java
    public abstract class TextUtils {
         private static String PATH;
         public static String[] KEYS;
         public static String[] WORDS;
         public static String[] PLAINTEXTS;
         public static float[] FREQUENCES;
          * Init KEYS, WORDS, PLAINTEXTS, FREQUENCES, and PATH,
          * with the files in the data folder.
         static {
              String line;
              PATH = TextUtils.class.getResource("../data/").toString();
              System.out.println(PATH);
              // When PATH is printed, it looks like this /home/tom/workspace/cryptanalysis/data/
              KEYS = FileUtils.readFileContent(PATH + "keys"); // Here is the first exception
              WORDS = FileUtils.readFileContent(PATH + "french_words");// Here is the second
              PLAINTEXTS = FileUtils.readFileContent(PATH + "french_texts");// Here is the third
              FREQUENCES = new float['['];
              try {
                   BufferedReader reader = new BufferedReader(new FileReader(PATH + "french_frequences"));// And the fourth
                   while(null != (line = reader.readLine()))
                        FREQUENCES[line.charAt(0)] += Float.parseFloat(line.substring(1));
              } catch (Exception e) {e.printStackTrace();}
    // Path to this class:
    // /home/tom/workspace/cryptanalysis/utils/FileUtils.java
    public abstract class FileUtils {
          * Read the content of the file denoted by the given path and
          * return an array of Strings containing each line.
          * @param path
          * @return an array containing all the lines from the file
         public static String[] readFileContent(String path) {
              try {
                   String line;
                   Vector container = new Vector(100, 100);
                   System.out.println(path);
                   BufferedReader reader = new BufferedReader(new FileReader(path));
                   while(null != (line = reader.readLine()))
                        container.add(line);
                   return (String[])container.toArray(new String[container.size()]);
              }catch(Exception e) {e.printStackTrace();return null;}
         ....

    vous �tes le type bienvenu
    (thats bablefish for "you're welcome dude")Wow! That means "vous �tes bienvenu" means "You are welcome here" (i.e., "welcome at the forum", or whatever), not the proper answer to "Thank you".
    The shortest form of "You're welcome" in the sense you intended it is "De rien". [literally, "of nothing"--so it would be something like if you said in English, "It was nothing."]

  • Any one has sample code of Multi-Thread Embbeded SQL in C ?

    We want to write multh-thread code using Embbeded SQL in C.
    The Open Client version is 15.7 SP100.
    The Sybase Document : "Embedded SQL/C Programmers Guide (Open Client) " said it supports Multiple SQLCAs,
    but has no sample code about this.
    Any one has sample code of Multi-Thread Embbeded SQL in C ?
    Thanks!

    Hi,
    I am asking around and will see if anyone has anything. Please note this though:
    http://infocenter.sybase.com/help/topic/com.sybase.infocenter.dc00371.1570/html/sdkrblnx/sdkrblnx39.htm
    Thanks,
    Dawn Kim

  • Firefox keeps blocking my ability to read emails using chtah. It doesn't start like this but it eventually blocks the code. this interferes with my email.

    Firefox blocks the code CHTAH, which is used by many of my email contacts to load pictures. This is not something that happens right away but over time. I need to delete Firefox and all saved information and reload the software in order to read my email. This has happened with several versions of Firefox and several versions of antivirus products.

    Reset the zoom level for each of those websites. <br />
    See this: https://support.mozilla.com/en-US/kb/Page+Zoom
    If you hold the Ctrl key and use the scroll wheel to move down the page, you will changed the zoom level of that domain.
    The Firefox [https://support.mozilla.com/en-US/kb/Page+Zoom Page Zoom] feature does a domain by domain level of saving the users preferred zoom level settings, there is no default Page Zoom level setting in Firefox, as with some other browsers.
    Try the Default FullZoom Level extension: <br />
    https://addons.mozilla.org/en-US/firefox/addon/6965
    Or the NoSquint extension: <br />
    https://addons.mozilla.org/en-US/firefox/addon/2592/

  • Siri make calls even when Iphone is blocked by code...

    I have discover a situation using Siri: when Iphone is blocked by code, if you pres the main button to activare Siri, she is activated and you can ask to make a phone call and she is doing. Normaly she has to ask for unblock code like for photos....

    Well that was a bust.  He was very polite and searched their databases for about five minutes (before taking my credit card info).  He came back and said there are a lot of incidents that mention this problem, but there were no solutions.  He apologized and said there does not appear to be a solution.  He suggested it might be corrected in a future update.  I'll keep looking and let you know if I find anything.

  • How to block material code

    hello all ,
    i want to know about how to block or delete material code .

    Hi,
    Am adding up..
    You can set the material status by using  this path
    IMG Path: Logistics General -> Material Master -> Settings for Key Fields -> Define Material Statuses.
    Please refer the below link...
    block material code
    Thanks.

  • Cancel anonymous SwingWorker thread?

    Hello,
    A beginner question.
    I have a button (A) calling a method, lets call it private void B().
    Inside the method B() I have this:
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { do some stuff }
    Anyway when I click the A button it calls the method b() and it works fine, the worker thread goes off and does what it needs to do.
    If I want to implement a Cancel button to cancel the SwingWorker thread started by private void B(), how should I do it?
    Thanks :)

    Using SwingWorker is rather neat, and surprisingly studious for a beginner. Make sure that you do non-Swing related work in doInBackground() and Swing-related stuff in done(), that mostly what SwingWorker is for.Yes, that is the way I'm using it together with setProgress to update a progress bar.Great. I hadn't even ever noticed the existence of this method! I learn someting new everyday.
    So, you're well ahead of me in terms of using the SwingWorker API! ;)
    Your problem is definitely with the Java lanuage, not the SwingWorker.
    Instead of using a local variable, make worker an attribute (of the class in which method b() is defined). Then in the action listener for the "Cancel" button, you can invoke the worker's cancel(boolean) method.
    I'm not quite sure what you mean exactly when you say an attribute. The method b() is defined within the class that displays the Swing GUI:
    public class ResyncWindow extends javax.swing.JFrame { } Do you want me to put the worker outside any methods?Yes, like this:
    public class ResyncWindow extends javax.swing.JFrame {
        SwingWorker<Void, Void> worker;
        public ResyncWindow() {
            ... // create launchButton, and wire its actionListener to trigger b()
            ... // create cancelButton, and wire its actionListener to trigger cancel()
        private void b() {
            worker = new SwingWorker<Void,Void>() {
                public void doInBackground() {
                    while (!isCancelled() { ..do stuff and set progress... }
            worker.execute();
            cancelButton.setEnabled(true);
            launchButton.setEnabled(false);
        private void cancel() {
             if (!worker.cancel()) {
                 ... // display error
             cancelButton.setEnabled(false);
             launchButton.setEnabled(true);
    }

  • Block T-code

    Hi all,
    How block T-Code authorization.
    Advance thanks
    BR
    Jack

    Dear,
    Which T .Code you wnat to block?
    You want to block the user authorisation for T.Code then  you can do through PFCG T-code. In PFCG authorization tab we neeed to maintain .
    SU21 - Authorization object.
    Please check this link,
    [T-Code authorization|Authorization Code]
    Regards,
    R.Brahmankar

  • What this block of codes of C output? thanks

    What is the output of this block of codes of C? what about short-circuit true of C
    when the user enter 5? i dont have C o r C++ so can anyone help me out, thanks.
    int fun (int *x ) { return (*x)++; }
    int main() {
    int a;
    a = 0;
    printf("%d\n",a); /* prints the integer a, with newline to the screen */
    scanf("%d",&a); /* scans an integer from the user into a */
    if ( (a>0) && fun(&a) ) printf("%d",a); /* prints the integer a conditionally */
    printf("%d\n",a);

    What is the output of this block of codes of C? what
    about short-circuit true of C
    when the user enter 5? i dont have C o r C++ so can
    anyone help me out, thanks.
    int fun (int *x ) { return (*x)++; }
    int main() {
    int a;
    a = 0;
    printf("%d\n",a); /* prints the integer a, with
    h newline to the screen */
    scanf("%d",&a); /* scans an integer from the user
    r into a */
    if ( (a>0) && fun(&a) ) printf("%d",a); /* prints
    s the integer a conditionally */
    printf("%d\n",a);
    }why would 5 cause a short-circuit?

  • How to write uninterruptable blocks of code in the RUN method of a THREAD?

    Hello people,
    It is better I explain my problem with example code
    public class MyThreadClass implements Runnable
    //some definitions
    public void run()
    //some codes
    /*HERE I WANT TO WRITE A CODE WHICH WILL BE RUN AS ORDINARILY
    FROM BEGINING TO THE END WITOUT ANY INTERRUPT*/
    //some codes
    Please help, if you can.
    Thanks in advance
    Tamer

    You can't write a block of uninterruptable code in Java.

  • Syncronized block of code

    Hello there ...
    Regarding of this topic. I've read that syncronized blocks helps to improve methods perfomance, but what I didn't understand was what do you pass to the sincronized line:
    public void method(){
              System.out.println("Not syncronized..");
    syncronized(this)//what is this?
          System.out.println("this is sincronized");
    }It supossed to pass a reference of the object?
    thanks in advance... any comment it's well recieved.
    vanhalt

    vanhalt wrote:
    Hello there.
    Thanks for replies. Your link was very useful... But now I didn't understand this piece of code:
    public void method(){
    syncronized(objReferenceA){
    //use non-shared resources
    syncronized(objReferenceB){
    }regarding this piece of code it's supposed that I'm obtaining the locks for the objA and objB ? ... Yes. Note that this particular code is only taking one lock at a time. It gets lock A, then releases it, then does some work, then gets lock B then releases it.
    and what happens with the lines of code that are not sincronized ? I mean other threads can access it ?..When a thread comes to one of those blocks, it will have to stop and wait if some other thread already has the lock that it's trying to obtain. If the two threads are obtaining two different locks (for example if their objReferenceA variables point to different objects) then both can execute concurrently.

  • How can we pass argument to static block of code????

    hi ,
    My question is we can use static initialization block for having functionality like constructors for initializing static variable ,but we cannot pass arguments to static initialization block then how can I create functionality like parametrized constructors.Whats the alternative shall I use a static method to perform this functionality,since all methods in given class are static and
    there is no need of creating instance of class.

    jduprez wrote:
    Hello Jussi,Salut Jérôme
    That's probably a more maintenable design.
    However what do you base your remark on - I'm struck by the word obviously?
    Is there some design principle from which this advice so naturally ensues that it is obvious ?Yes I read my posting later on and thought about changing it, since it's not necessarily an obvious solution. I was making assumptions that I didn't clarify from the OP.
    In the OP's case, the "state" on which those methods operate is apparently fixed, presumably at the beginning of the program, so what's wrong with all this staticness?
    I can list:
    - threading issues (a non-issue after some initialization phase), that you wouldn't have with immutable instances
    - harder unit-testing (that's not an OO design problem, more a methodology problem)
    - mix and confusion between static and non-static state if the class ever happens to have both, in future maintenance. All good points, I see all-static classes as a "code smell" and especially in this case when there's parametrization involved.
    Now we just need to have the OP explain his situation a bit better.

  • I want to know why it's happening me this error: Object synchronization method was called from an unsynchronized block of code.

    I'm developing a Smart Array (it's a request I cannot use a List of int that I know it's easier because I made both codes). I have done this class and below is the example of how I use it. The error is often in this line (153 from class):
    // Ensure that the lock is released.
    Monitor.Exit(array);
    If I use a List nothing wrong happens just when I translate to an array. Thanks for your help.
    SmartArray3.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    namespace SmartArray
    class SmartArray3
    private int[] array;
    private int size = 0;
    private int count = 0;
    public SmartArray3()
    Resize(1);
    public SmartArray3(int size)
    this.size = size;
    array = new int[this.size];
    public bool Resize(int size)
    try
    if (array == null)
    array = new int[size];
    else
    Array.Resize(ref array, size);
    this.size++;
    return true;
    catch
    return false;
    private void add(int value)
    try
    if (array == null)
    this.size = 1;
    Resize(this.size);
    array[0] = value;
    this.count++;
    else
    if (this.count == (this.size - 1))
    this.size *= 2;
    this.Resize(this.size);
    if ((this.count - 1) < 0)
    array[0] = value;
    else
    array[this.count - 1] = value;
    this.count++;
    catch (Exception ex)
    Console.Write(ex.ToString());
    throw new System.IndexOutOfRangeException("Index out of Range.");
    // Lock the array and add an element.
    public void Add(int value)
    // Request the lock, and block until it is obtained.
    Monitor.Enter(array);
    try
    if (array == null)
    this.size = 1;
    Resize(this.size);
    array[0] = value;
    this.count++;
    else
    if (this.count == (this.size - 1))
    this.size *= 2;
    this.Resize(this.size);
    if ((this.count - 1) < 0)
    array[0] = value;
    else
    array[this.count - 1] = value;
    this.count++;
    finally
    // Ensure that the lock is released.
    Monitor.Exit(array);
    // Try to add an element to the List: Add the element to the List
    // only if the lock is immediately available.
    public bool TryAdd(int value)
    // Request the lock.
    if (Monitor.TryEnter(array))
    try
    if (array == null)
    this.size = 1;
    Resize(this.size);
    array[0] = value;
    this.count++;
    else
    if (this.count == (this.size - 1))
    this.size *= 2;
    this.Resize(this.size);
    if ((this.count - 1) < 0)
    array[0] = value;
    else
    array[this.count - 1] = value;
    this.count++;
    finally
    // Ensure that the lock is released.
    Monitor.Exit(array);
    return true;
    else
    return false;
    public int Get(int index)
    try
    return array[index];
    catch (IndexOutOfRangeException ex)
    throw new System.IndexOutOfRangeException("Index out of range");
    Code for called the Class:
    private static int threadsRunning = 0;
    private SmartArray3 sa = new SmartArray3();
    private List<double> times;
    private static string[] titles ={
    "Add ", "Add failed ", "TryAdd succeeded ", "TryAdd failed "};
    private static int[][] results = new int[3][];
    //Event to Create Threads
    private void newTest()
    for (int i = 0; i < 3; i++)
    Thread t = new Thread(ThreadProc);
    t.Start(i);
    Interlocked.Increment(ref threadsRunning);
    private void ThreadProc(object state)
    times = new List<double>();
    DateTime finish = DateTime.Now.AddSeconds(10);
    Random rand = new Random();
    int[] result = { 0, 0, 0, 0};
    int threadNum = (int)state;
    while (DateTime.Now < finish)
    Stopwatch sw = Stopwatch.StartNew();
    int what = rand.Next(250);
    int how = rand.Next(25);
    if (how < 16)
    try
    sa.Add(what);
    result[(int)ThreadResultIndex.AddCt] += 1;
    times.Add(sw.Elapsed.TotalMilliseconds);
    catch
    result[(int)ThreadResultIndex.AddFailCt] += 1;
    else
    if (sa.TryAdd(what))
    result[(int)ThreadResultIndex.TryAddSucceedCt] += 1;
    else
    result[(int)ThreadResultIndex.TryAddFailCt] += 1;
    sw.Stop();
    results[threadNum] = result;
    if (0 == Interlocked.Decrement(ref threadsRunning))
    StringBuilder sb = new StringBuilder(
    " Thread 1 Thread 2 Thread 3 Total\n");
    for (int row = 0; row < 4; row++)
    int total = 0;
    sb.Append(titles[row]);
    for (int col = 0; col < 3; col++)
    sb.Append(String.Format("{0,4} ", results[col][row]));
    total += results[col][row];
    sb.AppendLine(String.Format("{0,4} ", total));
    Console.WriteLine(sb.ToString());
    private enum ThreadResultIndex
    AddCt,
    AddFailCt,
    TryAddSucceedCt,
    TryAddFailCt
    Federico Navarrete

    The array that you're calling Monitor.Enter under is not always the same array that you call Monitor.Exit on. When you resize an array using Array.Resize, you pass the variable in as a reference parameter (ref). The method then creates a
    new array object and assigns it to the array variable. Then, when you leave the synchronization block after resizing the array, your Monitor.Exit uses the new array rather than the one it originally entered
    and... boom.
    Instead of locking on the array itself, create a new private readonly field of type Object called "lock" within the SmartArray class and use that to lock on. It doesn't
    need to be readonly, but the keyword will prevent you from accidentally introducing this issue again.

  • Close a blocking wait thrad by another thread

    Hi all
    I have a lookup method which makes a blocking wait and I want to close this lookup if the content not available for 10 seconds.
    What I have done is put this lookup in a thread(LookupThread) and used separate thread(TimeCheckThread) for calculate the elapsed time.
    This is my idea
    public class LookupThread extends Thread
        Calendar cal = Calendar.getInstance();
        boolean closed = false;
        public TimeCheckThread getTimeChecker()
            return new TimeCheckThread();
        public void run()
            lookMethod(); // this is the blocking wait
        public class TimeCheckThread extends Thread
            long startTime = cal.getTimeInMillis();
            public void run()
                // strted looking for elapsed time
                while(true)
                    cal = Calendar.getInstance();
                    if(cal.getTimeInMillis()-startTime > 10000 & !closed)
                        // if 10 seconds elapsed close the thread which makes the blocking wait
                        LookupThread.super.stop();
                        closed = true;
                        // to exit from time check thread
                        break;
        public static void main(String args[])
            LookupThread v = new LookupThread();
            v.getTimeChecker().start();
            v.start();
    }The problem is closing of thread is deprecated.
    LookupThread.super.stop();So any idea to handle those blocking wait situations and assign a return time other than this approach?

    WirajR wrote:
    Also TimeCheckThread eats of CPU time for 10 seconds use a java.util.Timer instead
    >Also TimeCheckThread eats of CPU time for 10 seconds use a java.util.Timer instead
    Hi
    I think this is the most suit to my requirement. Totally different way, but acceptable.
    To EJP
    Ur solution seems great to replace following code segment
    public class TimeCheckThread extends Thread
            long startTime = cal.getTimeInMillis();
            public void run()
                // strted looking for elapsed time
                while(true)
                    cal = Calendar.getInstance();
                    if(cal.getTimeInMillis()-startTime > 10000 & !closed)
                        // if 10 seconds elapsed close the thread which makes the blocking wait
                        LookupThread.super.stop();
                        closed = true;
                        // to exit from time check thread
                        break;
        }like following
    public class TimeCheckThread extends Thread
           public void run()
                        TimeCheckThread.sleep(10000);
                        LookupThread.super.stop();
    }To Peter__Lawrey
    Why don't you make the blocking lookup block for only 10 seconds?Any idea to implement such blocking lookup block?
    My blocking operation is a looking for RTP video stream. It waits until server sends the video

Maybe you are looking for

  • Is it my cop of tea?

    got an old widescreen crt philips with a couble of scarts and composite input for video and audio got a wifi router which give internet with wpa security for 5 pc's using itune would like an easy to use system to play my music in the livingroom witho

  • Getting an error in startdb while restarting sap services

    hi Experts , while restarting my sap services it gets an error at startdb and log file is shown below                                                                                ABAP Database is not available via R3trans Starting SAP-Collector Dae

  • Using a baseclass, please help me.

    I have this structure DocumentInfoBean extends CoreEntityBean public field1; public field2; on the other side: CoreEntityBean public keyField2; public keyField3; Deployment tool only shows me field1 and field2; and of course I need keyField2 and 3 I

  • ABAP Class for BOR IMAGE

    Is there an ABAP Object class which wraps or implements the BOR IMAGE? ( In particiluar, I wan't to be able to use the display method. ) Thanks... ,..Mike

  • Is there a manual for the canon MX922

    Solved! Go to Solution.