Question on threading

Hi,
I recently saw a procedure (it is in a package) that records if a batch process started and updates a row when the batch process ends.
The way it does it is by inserting a row into a table and it keep the rowid of the row inserted into a global package variable.
So when the process ends, it uses the rowid from the variable to update the same row which was inserted.
But there are multiple programs which make use of this package to record the batch process entries.
Scenario:
One program started and made some entry and stored a value of rowid in the variable.
And before that process could update the entry, a new process started and inserted one more row with a new rowid.
And now the first process completes and it needs the rowid to update. But the previous one should be overwritten by the new rowid from the second process,
so it updates the second row, which is not what I would expect.
But I get the answer that Oracle knows which rowid to update.
It maintains different threads.
Is there any setting when the procedure is compiled or something which makes it function that way.
Any ideas ...
Thank you.

user10141630 wrote:
I understand that uncommited DML changes are not visible in other sessions.
But in this case, once the entry into a batch control table is made by the p[ackage and the rowid is stored in the package variable, the calling program commits the transaction. So now it is a commited change.
Now if a second program makes an entry in the batch control table, it will update the rowid from the first program.
But the ROWID is stored in a package global variable, which is never visible to another session (talking Oracle sessions here). So session #1 loads a ROWID in to a global variable, no other session gets to see that value, ever. Each session gets it's own initialized (when the package is first executed and loaded in to memory) global variable to play with and set it as it likes. So since session #2 can never see the ROWID that session #1 stored, it's not possible for it to make any modifications to that row (assuming the update is based on that global variable anyways).Cheers,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • Follow-up question to thread 'Sort by "total" in Answers'

    Seems I was a bit too quick in closing.
    Sorry for opening two threads on this, but I need to get this solved as I'm on a tight deadline here...
    The answer that pretty much solved my issue on sorting columns on sub-totals in Answers was:
    if you want to sort on sub-totals, follow this:
    i'm assuming that for that profitability column sub-total is sum of individual values for that segment..
    create other column in criteria tab:
    change it's fx to: sum(Profitability by Year, Sector)
    then, keep first sort order asc/desc on this column
    hide this column
    apply 2nd sort order asc/desc on normal profitability column..
    hope it resolve your issue.... I just have one more quick question:
    I can now sort according to sub-total, but how can I hide this new column from my table view? Clicking on the red 'x' button totally removes it as a filter.. The "hide" checkbox in the properties of the column simply grays the column out and shows it without any numbers.
    Thanks in advance
    - Magnus

    go to column properties (first option) > Column Format tab
    you find hide check box.. select and save.
    grays out the values in the column, which is correct and the same what we want..
    But, you should look at that in compound layout, not in edit properties of table...
    in compound layout, appears like it's hidden
    or
    achieve everything in pivot then exlude that particular column
    Edited by: Kishore Guggilla on Nov 29, 2010 7:18 PM

  • A question in threading

    Hi everybody,
    my problem is as follow, I have two classes myClass and myGUI
    myClass code is
    public class MyClass
         public void start()
              while (true)
                   // do some stuff
         public void stop()
              System.out.println("Hello from stop method!");
    }myGUI code is
    public class MyGUI extends javax.swing.JFrame
    MyClass cl = new MyClass();
    public static void main(String[] args)
                        MyGUI inst = new MyGUI();
                        inst.setLocationRelativeTo(null);
                        inst.setVisible(true);
    public MyGUI()
              super();
              initGUI();
    private void initGUI()
    // some GUI code
    myStartBtn.addActionListener(new ActionListener()
                             public void actionPerformed(ActionEvent evt)
                                  cl.start();
    myStopBtn.addActionListener(new ActionListener()
                             public void actionPerformed(ActionEvent evt)
                                  cl.stop();
    }as you can see, the start() method puts the program in an infinite loop, which makes me unable to call the stop() method using myStopBtn... So, I think this can be done using threads but actually I don't know how exactly am gonna do this
    So, any help will be appreciated.
    Thanks

    This has nothing to do with JSF.
    If you have a Concurrency specific question, post it in the Concurrency forum.
    http://forum.java.sun.com/forum.jspa?forumID=534
    If you have a Swing specific question, post it in the Swing forum.
    http://forum.java.sun.com/forum.jspa?forumID=57

  • Urgent question about Thread-safety

    Hi all,
    the new tiger release provides an "isReachable()" method for the "InetAddress" object.
    I've found, this method is not thread-safe (see the source and output below).
    It returns true for all threads, when multiple threads using this method with different adresses are running at a time and one of the addresses is reachable. This happens only on WinXp. Running on Linux, the output is like expected.
    I've tried to report this as a bug. But the gurus answered, taking care of thread safety would be a "programmers task".
    My question is, what can I do, to be thread-safe in my case?
    W.U.
    import java.util.*;
    import java.net.*;
    public class IsReachableTest_1 extends Thread{
        static volatile int inst=1;
        static final String NET_ADDR="192.168.111.";
        int instance=inst++;
        public void run(){
            for(int i=19;i<23;i++){
                try{
                    long start=System.nanoTime();
                    if(InetAddress.getByName(NET_ADDR+i).isReachable(1000))
                        System.out.println(""+instance+"--host found at:"+NET_ADDR+i+"--time:"+(System.nanoTime()-start)/1000000);
                    else
                        System.out.println(""+instance+"--no host at:"+NET_ADDR+i);
                }catch(Exception e){System.out.println(""+instance+"--ERROR "+e.toString());}
            System.out.println(""+instance+"--done.");
        public static void main(String[] args) {
            System.out.println(
                System.getProperty("java.vendor")+" "+
                System.getProperty("java.version")+" running on "+
                System.getProperty("os.name")+" "+
                System.getProperty("os.version"));
            Vector v=new Vector();
            System.out.println("\nTest 1: One after another:");
            for(int i=0;i<10;i++){
                IsReachableTest_1 t;
                t=new IsReachableTest_1();
                t.start();
                try{
                    t.join();
                }catch(Exception e){System.out.println("MAIN1: "+e.toString());}
            System.out.println("\nTest 2: All together:");
            inst=1;
            for(int i=0;i<10;i++){
                IsReachableTest_1 t;
                t=new IsReachableTest_1();
                t.start();
                v.addElement(t);
            for(Iterator i=v.iterator();i.hasNext();)
                try{
                    ((IsReachableTest_1)i.next()).join();
                }catch(Exception e){System.out.println("MAIN2: "+e.toString());}
                System.out.println("\nALL DONE");
    And here is the output, when running on WinXp:
    Sun Microsystems Inc. 1.5.0-beta running on Windows XP 5.1
    Test 1: One after another:
    1--no host at:192.168.111.19
    1--no host at:192.168.111.20
    1--host found at:192.168.111.21--time:2
    1--no host at:192.168.111.22
    1--done.
    2--no host at:192.168.111.19
    2--no host at:192.168.111.20
    2--host found at:192.168.111.21--time:4
    2--no host at:192.168.111.22
    2--done.
    3--no host at:192.168.111.19
    3--no host at:192.168.111.20
    3--host found at:192.168.111.21--time:1
    3--no host at:192.168.111.22
    3--done.
    4--no host at:192.168.111.19
    4--no host at:192.168.111.20
    4--host found at:192.168.111.21--time:1
    4--no host at:192.168.111.22
    4--done.
    5--no host at:192.168.111.19
    5--no host at:192.168.111.20
    5--host found at:192.168.111.21--time:3
    5--no host at:192.168.111.22
    5--done.
    6--no host at:192.168.111.19
    6--no host at:192.168.111.20
    6--host found at:192.168.111.21--time:1
    6--no host at:192.168.111.22
    6--done.
    7--no host at:192.168.111.19
    7--no host at:192.168.111.20
    7--host found at:192.168.111.21--time:1
    7--no host at:192.168.111.22
    7--done.
    8--no host at:192.168.111.19
    8--no host at:192.168.111.20
    8--host found at:192.168.111.21--time:1
    8--no host at:192.168.111.22
    8--done.
    9--no host at:192.168.111.19
    9--no host at:192.168.111.20
    9--host found at:192.168.111.21--time:1
    9--no host at:192.168.111.22
    9--done.
    10--no host at:192.168.111.19
    10--no host at:192.168.111.20
    10--host found at:192.168.111.21--time:1
    10--no host at:192.168.111.22
    10--done.
    Test 2: All together:
    1--no host at:192.168.111.19
    2--no host at:192.168.111.19
    3--no host at:192.168.111.19
    4--no host at:192.168.111.19
    5--no host at:192.168.111.19
    6--no host at:192.168.111.19
    7--no host at:192.168.111.19
    8--no host at:192.168.111.19
    9--no host at:192.168.111.19
    10--no host at:192.168.111.19
    2--no host at:192.168.111.20
    3--no host at:192.168.111.20
    6--host found at:192.168.111.20--time:924 <----- this host does not exist!!
    5--host found at:192.168.111.20--time:961 <----- this host does not exist!!
    10--host found at:192.168.111.20--time:778 <----- this host does not exist!!
    9--host found at:192.168.111.20--time:815 <----- this host does not exist!!
    2--host found at:192.168.111.21--time:37
    7--host found at:192.168.111.20--time:888 <----- this host does not exist!!
    8--host found at:192.168.111.20--time:852 <----- this host does not exist!!
    4--host found at:192.168.111.20--time:997 <----- this host does not exist!!
    1--host found at:192.168.111.20--time:1107 <----- this host does not exist!!
    3--host found at:192.168.111.21--time:38
    6--host found at:192.168.111.21--time:1
    5--host found at:192.168.111.21--time:1
    10--host found at:192.168.111.21--time:2
    2--host found at:192.168.111.22--time:3 <----- this host does not exist!!
    9--host found at:192.168.111.21--time:2
    7--host found at:192.168.111.21--time:1
    4--host found at:192.168.111.21--time:3
    1--host found at:192.168.111.21--time:39
    2--done.
    1--host found at:192.168.111.22--time:5 <----- this host does not exist!!
    1--done.
    10--host found at:192.168.111.22--time:40 <----- this host does not exist!!
    3--host found at:192.168.111.22--time:192 <----- this host does not exist!!
    6--host found at:192.168.111.22--time:75 <----- this host does not exist!!
    8--host found at:192.168.111.21--time:230
    5--host found at:192.168.111.22--time:155 <----- this host does not exist!!
    4--host found at:192.168.111.22--time:78 <----- this host does not exist!!
    9--host found at:192.168.111.22--time:77 <----- this host does not exist!!
    7--host found at:192.168.111.22--time:76 <----- this host does not exist!!
    10--done.
    6--done.
    4--done.
    5--done.
    3--done.
    7--done.
    9--done.
    8--no host at:192.168.111.22
    8--done.
    ALL DONE

    I created this test (it's basically the same as your class):
    import java.util.*;
    import java.net.*;
    public class IsReachableTest_2 implements Runnable {
        private final String[] addresses = new String[] {
             "www.sun.com",
             "129.42.16.99" // www.ibm.com which is not reachable
        public void run(){
            try {
                for (int i = 0; i < addresses.length; i++) {
                    final long start = System.nanoTime();
                    final String address = addresses;
         if (InetAddress.getByName(address).isReachable(5000)) {
         System.out.println(Thread.currentThread().getName() + ": Host found at: " + address +
              " --time: " + (System.nanoTime() - start) / 1000);
         } else System.out.println("no host at: " + address);
    } catch(Exception e){
    e.printStackTrace();
    System.out.println("Thread " + Thread.currentThread().getName() + " DONE");
    public static void main(String[] args) {
    System.out.println(
         System.getProperty("java.vendor") +
         " " +
         System.getProperty("java.version") +
         " running on " +
         System.getProperty("os.name") +
         " " +
         System.getProperty("os.version")
    for (int i = 0; i < 10; i++) {
         final Thread t = new Thread(new IsReachableTest_2(), "THREAD " + (i+1));
         t.start();
    And I get:
    Sun Microsystems Inc. 1.5.0-beta running on Windows 2000 5.0
    THREAD 1: Host found at: www.sun.com --time: 217653
    THREAD 3: Host found at: www.sun.com --time: 214404
    THREAD 6: Host found at: www.sun.com --time: 214900
    THREAD 4: Host found at: www.sun.com --time: 215901
    THREAD 5: Host found at: www.sun.com --time: 216666
    THREAD 10: Host found at: www.sun.com --time: 216620
    THREAD 9: Host found at: www.sun.com --time: 217405
    THREAD 2: Host found at: www.sun.com --time: 220705
    THREAD 7: Host found at: www.sun.com --time: 220845
    THREAD 8: Host found at: www.sun.com --time: 221384
    no host at: 129.42.16.99
    Thread THREAD 4 DONE
    no host at: 129.42.16.99
    Thread THREAD 6 DONE
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    Thread THREAD 5 DONE
    Thread THREAD 10 DONE
    Thread THREAD 9 DONE
    Thread THREAD 7 DONE
    Thread THREAD 3 DONE
    Thread THREAD 1 DONE
    Thread THREAD 2 DONE
    Thread THREAD 8 DONE
    HOWEVER: I was getting some strange results every so often. Results like:
    Sun Microsystems Inc. 1.5.0-beta running on Windows 2000 5.0
    THREAD 3: Host found at: www.sun.com --time: 261132
    THREAD 9: Host found at: www.sun.com --time: 264183
    THREAD 2: Host found at: www.sun.com --time: 266447
    THREAD 6: Host found at: www.sun.com --time: 266596
    THREAD 8: Host found at: www.sun.com --time: 267192
    THREAD 5: Host found at: www.sun.com --time: 268610
    THREAD 4: Host found at: www.sun.com --time: 269849
    THREAD 1: Host found at: www.sun.com --time: 280978
    THREAD 7: Host found at: www.sun.com --time: 272589
    THREAD 10: Host found at: www.sun.com --time: 273162
    THREAD 3: Host found at: 129.42.16.99 --time: 13657
    Thread THREAD 3 DONE
    THREAD 4: Host found at: 129.42.16.99 --time: 4123
    THREAD 2: Host found at: 129.42.16.99 --time: 9439
    THREAD 5: Host found at: 129.42.16.99 --time: 6681
    THREAD 8: Host found at: 129.42.16.99 --time: 7655
    THREAD 6: Host found at: 129.42.16.99 --time: 8627
    THREAD 9: Host found at: 129.42.16.99 --time: 10586
    Thread THREAD 4 DONE
    Thread THREAD 2 DONE
    Thread THREAD 5 DONE
    Thread THREAD 8 DONE
    Thread THREAD 6 DONE
    Thread THREAD 9 DONE
    no host at: 129.42.16.99
    Thread THREAD 7 DONE
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    Thread THREAD 10 DONE
    Thread THREAD 1 DONE
    Usually the first run after I had compiled the class (!?) This isn't a thread safety problem.

  • A question about thread safety and the Acrobat SDK

    Hi All,
    On page 12 of this FAQ: http://www.adobe.com/devnet/acrobat/pdfs/Acrobat_SDK_developer_faq.pdf
    It says that Use of any Acrobat product in a multithreaded way is technically impossible.
    I'm currently writing a command line application to perform some basic data gathering on a PDF file. The Application only makes use of a PDDoc object, and never calls on any other kind of object (i.e. AVDoc).
    The application itself is not multithreaded. All of the logic runs in a single thread.
    However, the application will be called (via the command line) from another application that /is/ multithreaded. I think that this might be fine, but I wasn't sure. In this case, would this count as a single thread, but spread across multiple processes? And if that is the case, would that be OK with the SDK?
    Or would having multiple invocations/calls into the Acrobat DLLs cause the same issue as a multi-threaded application?
    Unfortunately, I haven't done a lot of work with threads before. This might be a very silly question.

    The application would be called from a perl script that is used to automate several tasks. The app is a console application, written in C# w/ the Acrobat COM components, and Visual Studio 2005.
    The console application uses the Acrobat SDK to instantiate a PDDoc object, open a PDF, and get information about the document. It then returns results back to the console.
    So, the perl script just calls: "C:\pdfinfo.exe -f=myPdf.pdf" and pipes the result to a log file.
    In this case, it never creates a new instance of the Acrobat application, but it does use the SDK.
    The reason that I was concerned was that the perl script is multi-threaded. I wasn't sure if acrobat was just sensitive to multiple threads inside a single process, or if it was unable to handle multiple processes as well.
    PDL's answer suggests that I should be fine as long as a new process is started each time. This is good to hear.

  • Very Basic Question on Threads and Object Manipulation between classes

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

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

  • Some question on thread

    i think threads are unpredictable.say, the following code. some questions on the code.
    public class Rpcraven{
         public static void main(String argv[]){
         Pmcraven pm1 = new Pmcraven("One");
         pm1.run(); // line1
         Pmcraven pm2 = new Pmcraven("Two");
         pm2.run();  // line 2
    class Pmcraven extends Thread{
    private String sTname="";
    Pmcraven(String s){
         sTname = s;
    public void run(){
         for(int i =0; i < 2 ; i++){
              try{
               sleep(1000);
              }catch(InterruptedException e){}
              yield();
              System.out.println(sTname);
    }question 1 > note line 1 and line 2 . does this two threds are staarted at the same time ? or line 1 first and line 2 second as in the code ? this is very much important to me.
    question 2 > ok, whoever goes first , now lets come to the try-catch block . there is sleep() who will sleep first ? so i need to know which thread is going to sleep first ? bcoz then i can say who will get the yield() method.
    i find difficult to predict the output of this thred.
    Output of One One Two Two.
    one more thing, threads are always called by start() method ( run() is called implicitly) . here start() is not usued . still the code is working . how ?

    question 1 > note line 1 and line 2 . does this two
    threds are staarted at the same time ? or line 1 first
    and line 2 second as in the code ? this is very much
    important to me.If it's important, you are doing something wrong...
    First, you shouldn't call the threads' run() method, that doesn't "start" the thread, it just calls run(). Use start() instead.
    The threads are sort of started in order, but probably not in the way you think.
    Think of it like this: there is a list of threads in the JVM. start() puts the thread in the list. After that, the CPU of your computer can run any thread in the list, for as long as it feels like. The CPU might run thread 1 for a few instructions, then thread 2 for a while, or it might start with thread 2, ... If you have a multi-CPU machine, the threads are run at the same time. It's unpredictable, except when you do explicit synhcronization or waiting.
    question 2 > ok, whoever goes first , now lets come to
    the try-catch block . there is sleep() who will sleep
    first ? so i need to know which thread is going to
    sleep first ?This is unpredictable. You can't know it. It will vary from run to run.
    If you need two threads to do something in a predictable order, you'll need to do synchronization and waiting.
    one more thing, threads are always called by start()
    method ( run() is called implicitly) . here start()
    is not usued . still the code is working . how ?You are not starting the threads, you are calling their run() methods sequentially.

  • Question on Thread synchronization

    Why the use of synchronized key word doesnt guarantee sequential
    execution of the code across multiple threads , unless we use wait and
    Notify ?

    The question is non-sensical - if you want sequential execution then there absolutely no point in using multiple threads in the first place.

  • Question on Thread concurrency

    If two threads execute the below method increment() concurrently, how many different final values of X are there? You may assume that initially X has value 0.
    void increment()
    int temp = x;
    temp = temp + 1;
    x = temp;
    }

    That's enough of these questions. It's not a homework service. Locking this thread.

  • Question on Thread

    Hi All
    I got a doubt while implementing threads, so thought of getting it cleared before i do some progress. I have a method from where the new thread is getting called and in the next line i have return statement.
    Method(){
    Calling thread ();
    return statement;
    What happens here? I mean Does the parent process completes before the child process?
    Thanks
    Simi

    user11138361 wrote:
    I exactly mean the same
    int foo() {
    Runnable r = new MyRunnable();
    Thread t = new Thread(r);
    t.start();
    return 1;
    My question was If the child process is running then how the parent process(Px) will complete ?There is no child process. You're creating a thread, not a process.
    That point aside, I don't understand your question. The current thread and the new thread are totally independent of each other. Why would you expect that one can't complete while the other is still running?
    Also note that the parent thread is NOT the same as that foo() method. The thread doesn't necessarily end when the foo() method does. It can, though, and I don't know why you'd think otherwise.
    EDIT: My guess is that what you're really confused about is, "How can method foo() end when one of its 'steps' (that is, the new thread) is still executing?" The answer is that all of its steps are done, even if the other thread is still running.
    foo()'s step of calling t.start() has finished. That doesn't mean the new thread has finished, however. The start() method says, "create a new, +independent+ thread of execution and set it running." As soon as it does that, start() is done, and now the new thread is running (or eligible to run) independently of the current thread.
    Imagine I have a list of chores: Take out trash; Wash dishes; Vacuum living room. That list is the foo() method. You are a new Thread object. After I wash the dishes, I tell you "Go to the store, and buy apples, milk, eggs, chicken, and bread." You leave to do your work, and as soon as I have told you what to do, I continue with my tasks. We do our work independently of each other, and I can finish the chores on my list without waiting for you to come back from the store.
    Edited by: jverd on Mar 21, 2011 11:27 AM

  • Question about Threads

    Hi,
    imagine that I have a class as below:
    public class MyVector
    private IntegerVector vect;
    public Synchronized void write(){
    vect.f();
    public Synchronized void read(){
    vect.g();
    Where f and g are non Synchronized and non-static public methods of IntegerVector .
    Imagine that two threads as below:
    thread one :
    class ThreadOne extends Thread
    public ThreadOne(MyVector v)
    this.v=v;
    public void run()
    v.write();
    class ThreadTwo extends Thread
    public ThreadTwo(MyVector v)
    this.v=v;
    public void run()
    v.read();
    My question is that if there will be any conflict between thread1 and thread2 for having the lock on
    object MyVector v ?the methods read and write are Synchronized but they call non-Synchronized methods f() and g()
    of field "IntegerVector vect" of "MyVector v "!
    Thanks,
    Behnaz

    bandarurm wrote:
    jverd wrote:
    bandarurm wrote:
    @OP - Also, remember that there are only two types of locks (aka monitors), which are Object level lock and Class level lock. No. All locks are identical.Could you explain this further? As I thought there is a class level lock (java.lang.Class) for a class with static synchronized methods. And, there is an object level lock, which is a built-in lock that every object has in java, by default.Whenever you synchronize a block of code or a method, you're just obtaining some object's lock. Synchronized methods are just shorthand for obtaining particular objects' locks.
    Synchronization is always the same. Declaring a method synchronized is just shorthand for what you could do by explicitly syncing a block of code on a particular object.
    class Foo {
      synchronized void bar() {
        // body
      // is the same as
      void bar() {
        synchronized (this) {
          // body
      // and
      static synchronized qux() {
        // body
      // is the same as
      static qux() {
        synchronized (Foo.class) {
          // body
    }In all cases, you're just syncing on an object, and which object doesn't matter, except to other methods or blocks that sync on the same object. Everything else is identical.
    The fact that synchronized static methods obtain one particular lock and non-static ones obtain a different one is not indicative of different kinds of locks. It's always just some object's lock, and no lock behaves differently from any other.
    Edited by: jverd on Apr 20, 2009 10:46 AM

  • Questions about thread priority...

    Situation 1) setPriority(int adsa)
    public class ThreadPrioDemo1 {
          static class Demo1 implements Runnable{
          public void run(){ //blablabla}
         public static void main(String[] asdf){
              Runnable r = new Demo1();
              Thread myThread = new Thread(r);
              Thread mainT = Thread.currentThread();
              //mainT's priority is 5, so as myThread.
            mainT.setPriority(10);
    //mainT's priority to MAX, this simultaneously changes myThread to 10 as well.
            //or
            myThread.setPriority(10);
    //myThread priority to MAX, however, this does not change mainT to 10
    }Question 1), why if main Thread is set to a certain priority, the thread it creates automatically change its priority to the same as well, but the reverse is different??
    Situation 2) this is slightly more complex
    public class ImplementingRunnable {
         public static void main(String[] args) {
         Thread mainT = Thread.currentThread();
              for(int ii=0 ; ii<args.length ; ii++) {
                   Runnable r = new MyRunnable(args[ii]);
                   Thread t = new Thread(r);
                t.setDaemon(true);
                //t.setPriority(Thread.MAX_PRIORITY);
                   t.start();
    }and
    public class MyRunnable implements Runnable {
        public void test(){
        System.out.println("test");
         String message;
         public MyRunnable(String msg) {
              message = msg;
         public void run() {
              Thread me = Thread.currentThread();
              try {
                   for(int ii=0 ; ii<10 ; ii++) {
                       //case (1) me.setPriority(Thread.MIN_PRIORITY);
                        me.sleep(3);
                        System.out.println(message);
                        //case (2) me.setPriority(Thread.MIN_PRIORITY);
              } catch (InterruptedException ie) {
    }In class ImplementingRunnable, how is the commented code line related or counter-related with the commented case 1 code line in MyRunnable??
    Please help
    thanks

    Let me speak my question again very simply:
    1)
    Say I have two threads, 1 is main() thread, the program entry point, 2 is another thread created by main().
    Now, the default priority for both two is 5. If I change the priority for main() to a certain level, the other thread created by it automatically change its priority to the same level? why? and however, the reverse (in this case, if I change the priority for the thread created by main()) is not.
    2)
    public class Demo{
    static class MyThread implements Runnable{
    public void run(){//some thing}
    Thread t = new Thread(this);
    t.setPriority(10);
    public static void main(String[] afd){
    Runnable r = new MyThread();
    Thread t1 = new Thread(r);
    t1.setPriority(1);
    }What can you say about both bold code lines?
    If I use println() to track the Priority, the final priority, that is, t1, is 1. It is logical, however, the program behaves differently without the bold code line in the static class MyThread, despite the final priority for t1, is the same, 1.
    Any help by now??
    thanks alot

  • Question on thread safety with Sevlet action method

    I have an application that runs well but seems to have trouble with multiple users and I suspect that there is some thread safety issue involved.
    It is a Struts application and I have all of my execute methods of the Acton classes are all synchronized which I thought would take care of any cross user issues but it does not seem to have done that.
    The Action classes do have some instance variables which may be the problem as well as possibly a few utility string classes with static methods that are not synchornized. I keep some db connection cached in the session object but this should not be shared between users.
    My question is, with the execute method synchronized how or where could I be getting crosstalk between users (each with their own sessions)?
    I was thinking of packaging my Action class as seperate object with the actual Action class just allocate what I need (messages and locale) and pass them through a freshly instantiated "old action class". That should solve any instance variable cross talk.
    I am assuming that any local variables in the execute method would not have any exposure as they should be thread specific and allocated on the runtime stack for that thread call.
    Am I missing anything important?
    Thanks in advance
    ---John Putnam

         * Creates a new instance of a {@link javax.xml.parsers.DocumentBuilder}
         * using the currently configured parameters.
        public DocumentBuilder newDocumentBuilder()
            throws ParserConfigurationException
            /** Check that if a Schema has been specified that neither of the schema properties have been set. */
            if (grammar != null && attributes != null) {
                if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_LANGUAGE)) {
                    throw new ParserConfigurationException(
                            SAXMessageFormatter.formatMessage(null,
                            "schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_LANGUAGE}));
                else if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_SOURCE)) {
                    throw new ParserConfigurationException(
                            SAXMessageFormatter.formatMessage(null,
                            "schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_SOURCE}));               
            try {
                return new DocumentBuilderImpl(this, attributes, features, fSecureProcess);
            } catch (SAXException se) {
                // Handles both SAXNotSupportedException, SAXNotRecognizedException
                throw new ParserConfigurationException(se.getMessage());
        }It appears to be thread-safe. The 'attributes' and 'features' instances variables are hashtables, which are synchronized. Unless you are modifying DocumentBuilderFactory itself in another thread (say, changing whether it is namespace aware), I do not see any issues with a simple call to newDocumentBuilder().
    - Saish

  • Nub question concerning threads.

    I recently completed my first Comp Sci. class in Java and have decided to try to continue learning on my own. I am now trying to make a pong game, using a turorial. Unforunately my course did not cover threads in any way, shape, or form. I am able to get the beginning of the program to work (code posted below) and have no problems with it; however, I do have a few questions concerning what certain elements of the code do.
    1. Can someone please give a definition of a Thread in "Dummy" speach? I've looked up definitions and I can't seem to really grasp what they are and what they are used for.
    2. In my program there are two lines (32 & 79) where the thread priority is changed. Can someone explain what that means and how it affects my applet?
    import java.applet.*;
    import java.awt.*;
    public class BallApplet extends Applet implements Runnable
         //Declare variables to change posistion
         int x_pos = 10;
         int y_pos = 100;
         int radius = 20;
         boolean rWall = false,
         //The second image of the ball
         private Image dbImage;
         private Graphics dbg;
         public void init() {}
         public void start()
              Thread th = new Thread(this);
              th.start();
         public void stop() {}
         public void destroy() {}
         public void run ()
              Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
              while(true)
                   while (rWall == false )
                        if (x_pos == 700)
                             rWall = true;
                        else
                             x_pos= x_pos + 5;
                             // repaint the applet
                             repaint();
                             try
                                  // Stop thread for 20 milliseconds
                                 Thread.sleep (20);
                             catch (InterruptedException ex)
                                 // do nothing
                             // set ThreadPriority to maximum value
                             Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
                   while (rWall == true)
                        if (x_pos == 0)
                             rWall = false;
                             lWall = true;
                        x_pos = x_pos - 5;
                        repaint();
                        try
                             Thread.sleep(20);
                        catch (InterruptedException ex)
                        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
         public void update(Graphics g)
              //initialize buffer
              if (dbImage == null)
                   dbImage = createImage(this.getSize().width,this.getSize().height);
                   dbg = dbImage.getGraphics();
              //clear screen in background
              dbg.setColor (getBackground());
              dbg.fillRect (0, 0,this.getSize().width,this.getSize().height);
              //draw elements in background
              dbg.setColor (getForeground());
              paint(dbg);
              //draw image on screen
              g.drawImage(dbImage,0,0,this);
         public void paint (Graphics g)
              g.setColor (Color.red);
              g.fillOval(x_pos - radius,y_pos - radius,2*radius,2*radius);
    }Thanks for any help, it is greatly appreciated.

    Questie,
    Please control yourself. Please.??
    As the program runs it is one thread. (You canthink
    of each thread as an independent program if youlike.
    This is not 100% accurate but close enough that
    it
    might help you understand)
    It will only confuse the OP
    You are a flat out wrong for a number of reasons.
    1) You seemed to miss the part where I did say that a
    doubling in peformance is fictious and is dependent
    on a number of factors.As i was telling that would only confuse the OP.Its better to be 100% precise when you explain to an OP
    2) You don't understand how a multi-process OS works
    in the least.Assumptions as usual
    3) You don't understand how processors work in the
    least.Well,what was i saying?
    2 and 3 are important because your point about
    context switching is not valid. First of all because
    this happens anyway because your program is not the
    only thing running the processor. Second because of
    the first point each thread gets a timeslice, you may
    with multiple threads each get a timeslice and these
    slices may (and often do) add up to more total time
    then the first got by itself.When you consider a solution to a problem the average and the worst case has more weightage than the best case.You are taking the best case assumption here-"because ofthe first point each thread
    gets a timeslice, you may with multiple threads each
    get a timeslice and these slices may (and often do)
    add up to more total time then the first got by itself".Now dont stop whining that you werent.Never take the best case always coz its the average and worst case which checks if the system festers to a condition beyond rectification
    For example (these numbers are fictional but I am
    trying to explain it so don't go off all half-cocked
    again please)
    Program with one thread. Each thread gets 100 cycles
    per second.
    Program with four threads. Each thread gets 50 cycles
    per second.
    The second program will finish in half the time as
    the first. Because even though each thread is slower
    as a whole the program is getting twice the cycles
    of the processor as before. You are taking the best case again and moreover its the cpu scheduling algo which decides the time slice and not you sitting on the CPU.I have a vague feeling that you have an idea that you are sitting on the CPU deciding the Time Slice.
    You need to understand something important here. Alot
    of the time when you are doing things in a program,
    and this doesn't just apply to IO here, you don't
    have to use the processor for each step. There is
    some shifting around of things to get them ready to
    be executed by the processor. A more advanced
    representation of this is to be found with
    Hyperthreading. Hyperthreading processors (single
    core) are of course single core but they act as if
    they were multi-core (multi processes) because while
    only one process is actually executing at one time
    the others are pipelined in such a way to make sure
    that the executing core of the processor has the
    least amount of idle time possible.Digression
    So that means on a basic processor each time you add
    2 numbers it takes 5 steps. And the processor core is
    idle 80% of the time.
    From where did you get that 80%?Stop coming up with your own numberes.This is no number game
    So for example while some data is being placed in the
    outbox new data is also being collected and is at
    step 2 already. In this model while we are still on a
    single core the core is now idle only 60% of the time[b]From where did you get 60% now
    So yes threading is very useful for IO and other
    operations that may block your program but they have
    more use than just that. Parallel execution can and
    will have some performance advantages (if designed
    properly) even on a single core processor without
    hyperthreading. In a well written multithreaded
    program when you add hyperthreading and multiple
    cores or multiple processors to the mix then you
    really have something.I never said it wont.Read properly what i have posted.I told dont take the best case always.You need to consider that too but the other two carries more weightage
    Please don't feel you ever have to post to correct me
    again thanks.^^
    Get ride of this self conceited attitude.Even if you have it dont make it public.Its not that you are always right cotton.I am not saying that you are wrong.If you have read my first reply i mentioned that i knew that you gave that example just to make the OP understand.The problem with that is that if the OP is unable to fathom out what you mean he is going to misconstrue whatever you have said and that propogates

  • Oracle 8.1.7 OCI question: Some threads hang in OCIServerAttach indefinetly after rem

    Configuration: MS Win2k SP2, MS Visual C++ 6.0 SP6, Oracle 8.1.7 via OCI
    I have 128 threads doing the following:
    1) Create environment (OCI_THREADED, OCI_ENV_NO_MUTEX), setup handles, try to connect to remote database 2) If connect fails, log the error message and try again after 2 seconds 3) Execute simple stored procedure 4) Disconnect from remote database ( + cleanup of all handles including environment ) 5) ... repeat from 1)
    When I go to the remote database and perform shutdown of the whole operating system (by choosing shutdown in Windows), something peculiar happens. First I get: ORA-12500 and ORA-12541 error messages. Then most of the channels go to ORA-12535 error message and they loop in that message until I exit the application. However, some of the threads remain hanging in OCIServerAttach function and do not allow my application to exit.
    Needless to say, OCIBreak function doesn't help here (I've tried).
    When I attach the debugger to the hanging process, I get the attached stack trace. It looks like some sockets remain hanging - a terrible thing to happen.
    In the attachment are also Oracle error descriptions that I mentioned.
    I would be thankful for any suggestions here...
    -- Tomislav.
    "Real sharpness comes without effort,
    No growth without assistance,
    No action without reaction,
    Now give yourself up and find yourself again."
    "Crouching tiger, hidden dragon"
    NTDLL! 77f827e8()
    MSAFD! 74fd8e33()
    WS2_32! 75031275()
    ORANTCP8! 6470565f()
    ORANTCP8! 64703536()
    ORAN8! 60b78f5a()
    ORAN8! 60b7c8a8()
    ORAN8! 60b44d24()
    ORAN8! 60b3fd0a()
    ORAN8! 60b3f474()
    ORAN8! 60b157a0()
    ORAN8! 60b61c7c()
    ORACLIENT8! 60429b1e()
    ORACLIENT8! 604b4695()
    ORACLIENT8! 604b9ece()
    ORACLIENT8! 604823a3()
    ORACLIENT8! 60429f64()
    ORACLIENT8! 60401340()
    OCI! 015059ab()
    CLibOCI::OCIServerAttach(OCIServer * 0x0dff13e0, OCIError * 0x0dff15d4,
    unsigned char * 0x0de9b810, int 21, unsigned int 0) line 282 + 28 bytes
    FCALLDLL! 014d2c03()
    MSVCRT! 7800a3c0()
    KERNEL32! 77e8758a()
    "TNS-12500 TNS:listener failed to start a dedicated server process
    Cause: The process of starting up a dedicated server process failed. The executable could not be found or the environment may be set up incorrectly.
    Action: Turn on tracing at the ADMIN level and re-execute the operation. Verify that the Oracle Server executable is present and has execute permissions enabled. Ensure that the Oracle environment is specified correctly in LISTENER.ORA. The Oracle Protocol Adapter that is being called may not be installed on the local hard drive. Check that the correct Protocol Adapter are successfully linked. If the error persists, contact Oracle Customer Support.
    TNS-12541 TNS:no listener
    Cause: The connection request could not be completed because the listener is not running.
    Action: Ensure that the supplied destination address matches one of the addresses used by the listener. Compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on the remote machine.
    TNS-12535 TNS:operation timed out
    Cause: The requested connection could not be completed within the timeout period specified by the CONNECT_TIMEOUT parameter in LISTENER.ORA. This error arises from the TNSLSNR.
    Action: Either reconfigure CONNECT_TIMEOUT to be 0, which means wait indefinitely, or reconfigure CONNECT_TIMEOUT to be some higher value. Or, if the timeout is unacceptably long, turn on tracing for further information."

    Hi,
    What is going on in your case is :
    1. Oracle library (OCI) is failing to identify a Dead Connection properly all the time.
    2. According to the errors you have received, all of them seems to be appropriate to what you have described in your message.
    a. TNS failed to start a dedicated server process. This error is returned when the number of server processes are excessive or memory is low etc - I am not sure why this is returned to you
    b. TNS listener is not available - May be the listener has already shutdown, since the system is being shutdown.
    c. TNS operation timed out. This will be returned by your local TNS client library, which says CONNECT(socket operation) failed, since the other end has already SHUTDOWN.
    Getting an error is good for you, since you can always sleep 2 seconds and reconnect.
    The hanging thread is due to a problem that Oracle folks call as DCD(Dead COnnection Detection) logic. The DCD can be turned on by setting sqlnet.expire timeout to be some number of minutes in the sqlnet.ora file. Please check on the Metalink on the DCD issue.
    What I have personally seen is that DCD does not always work, even if turned ON.

  • Challanging question about Threads.  Can anyone help?

    Hello,
    I've been learing how to use threads and I have run into a little rut. I am making a game that listens for clicks of the mouse on the board AND allows people to talk to each other in a chat box.
    I've made a chatThread and in the public void run() method I can do the following...
    public void run(){
    while(true){
    try{
    chatText.append(ServerIn.readLine()+"\n");
    catch (Exception h){}
    this pastes whatever the other person wrote into the public chattext area. now my problem is this. I need another thread that listens for button clicks. If the button is clicked on one side, the other side needs to be able to read that click and perform a certan task. I only have 1 thread running, but I have made an instatance of PrintWriter for the text and DataInputStream for the integer value. I have tried things like this and they really don't like me. (they cause faluts and whatnot)
    public void run(){
    while(true){
    try{
    chatText.append(ServerIn.readLine()+"\n");
    ServerIn2a.readInt();
    catch (Exception h){}
    Sometimes the integer will read into the ServerIn2a and then when i try to chat it can't read into the ServerIn varialble.
    Do I need to make two seperate thread and somehow pause one and run one, then pause the other?
    Thanks for your help!

    Ok, sorry, here is a better description of what my program looks like (the parts that concern this topic)...
    public class Game extends JApplet implements ActionListener, Runnable{
    PrintWriter ClientOut = null; // to send messages to the server
    BufferedReader ClientIn = null; // to receive messages from the server.
    PrintWriter ServerOut = null; // to send messages to the client
    BufferedReader ServerIn = null; // to receive messages from the client.
    DataInputStream ClientIn2a = null; // to send messages to the server
    DataOutputStream ClientOut2a = null; // to receive messages from the server.
    DataInputStream ServerIn2a = null; // to send messages to the client
    DataOutputStream ServerOut2a = null; // to receive messages from the client.
    //On the main screen, if they press the "host" button they become the host and the this happens.....
    //I want these two lines to read text from a dialog box and then pass that text to the other person      //playerinput from a dialog box so it can be passed
    ServerIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    ServerOut = new PrintWriter(clientSocket.getOutputStream(),true);
    //When they click on a button, I am trying to read the buttons coordinate which will be a Integer value. I //I want to get that integer value to the other person so I make these DataInput and Output variables.
    ServerIn2a = new DataInputStream(clientSocket.getInputStream());
    ServerOut2a = new DataOutputStream(clientSocket.getOutputStream());
    //now I made a thread that is always supposed to listen to perform the action of sending the text to
    //the appropriate text listener and to send the integer to the appropriate DATAINPUT listener.
    Thread ServerThread = new Thread(this)
    ServerThread.start();
    //on the main screen, if they press the client button......
    ClientIn = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
    ClientOut = new PrintWriter(serverSocket.getOutputStream(),true);
    ClientIn2a = new DataInputStream(serverSocket.getInputStream());
    ClientOut2a = new DataOutputStream(serverSocket.getOutputStream());
    //now I made a thread that is always supposed to listen and perform the action to send the data to the
    //other person
    Thread clientThread = new Thread(this);
    clientThread.start( );
    //here is the actionPerformed method. They press enter in the text area box and this gets run.....
    if(player==1){
    //THE TEXT THEY TYPE FIRST GETS PASTED INTO THEIR OWN CHAT AREA
         chatText.append(HostUserName+": " + messageField.getText() + "\n");
         //NOW I WANT TO SEND WHEY THEY TYPE TO THE OTHER PERSON
    try{
    ServerOut.write(HostUserName+": " + messageField.getText()+"\n");
    ServerOut.flush(); }
    catch(Exception e){Mbox.showMessageDialog(null,"Chatting error","connect",1);}
    //here is my run method (this is where I think I am having my problems and that I need help with.
    public void run(){
         if(player == server){
         while(true){
         try{
         //THIS IS WHERE THE INTEGER SHOULD BE READ INTO
                   performAFucntion(ServerIn2a.readInt());}
              catch(Exception h){}
              //THIS TRY STATEMENT IS WHERE THE TEXT SHOULD BE READ
         try{   
              chatText.append(ServerIn.readLine()+"\n"); }
         catch (Exception h){}
    //ELSE YOU ARE THE OTHER PERSON AND YOU DO THE EXACT OPPOSITE OF ABOVE
    OK! Now that the code is out of the way. My problem.... Sometimes when I click on a button, the ineger value gets assigned to the ServerIn.reasline and funny symbols pop up in the other persons text area. And then when I try to type text in my text box after I get the wierd symbols into my chat text area, the CATCH (Exceptoin E) from my actionPerformed function that deals with sending the text gets activated and I see the dialog box that tells me there was an error.
    I THINK my error is in my run statement. I think everytime I write something, wether it be an integer or a text, the first .READLINE( ) that gets encountered in my run statement reads it. I think I have to have the WHILE(TRUE) statement or else it wont continuoulsy try to read in data.
    Can anyone tell me if I need to somehow make two threads, one that listens for the text and a seperate one that listens for the integer value?
    I hope this is a little bit more clearer than my last letters. Thanks for being patient with me.

Maybe you are looking for