Multiple threads access the same method.

Hello,
I have been trying for a long time to find out multiple threads access the shared data.
I have written a sample code, there I my intention is that method has to be accessed
onlny one thread at a time., mean one thread finished the job, then next thread can
access the shared source. But for this code I am not getting the desired out put what I want. But if I am using synchronized block I am getting the output. Please correct where I got mistake. Please see my code.
public class TestThread implements Runnable {
     Shared r;
     public TestThread() {
          r = new Shared();
     public static void main(String args[]) {
          Thread t1 = new Thread(new TestThread());
          Thread t2 = new Thread(new TestThread());
          t1.setName("A");
          t2.setName("B");
          t1.start();
          t2.start();
      * (non-Javadoc)
      * @see java.lang.Runnable#run()
     @Override
     public void run() {
          // TODO Auto-generated method stub
          r.count();
class Shared {
     public synchronized void count() {
          String name = Thread.currentThread().getName();
          System.out.println(name + ":accessed...");
          try {
               for (int i = 0; i < 5; i++) {
                    System.out.println(name + ": " + i);
          } catch (Exception e) {
               // TODO: handle exception
}Thanks
Bhanu lakshmi.

It depends on what you synchronize. Non-static methods synchronize on the object, so if you're using several objects, you'll be able to call each from their own thread.
Make your method synchronized or use only a single object and see the difference.

Similar Messages

  • Problem with multiple threads accessing the same Image

    I'm trying to draw into one Image from multiple threads. It works fine for a while, but then suddenly, the image stops updating. Threads are still running but the image won't update. I'm using doublebuffering and threads are simply drawing counters into Image with different speed.
    It seems like the Image gets deadlocked or something. Anyone have any idea what's behind this behavior or perhaps better solution to do such thing.
    Any help will be appreciated.

    Sorry Kglad, I didn't mean to be rude. With "No coding
    errors" I meant the animation itself runs with no errors. I'm sure
    you could run the 20 instances with no freezing (that's why I put
    the post :) ) But I'm affraid it is an animation for a client, so I
    cannot distribute the code.
    Perhaps I didnt explain the situation clearly enough (in part
    because of my poor english...).-
    - By 20 instances I mean 20 separated embedded objects in the
    html
    - The animation is relatively simple. A turned on candle, in
    each cycle I calculate the next position of the flame (that
    oscilates from left to right). The flame is composed by 4
    concentric gradients. There is NO loops, only an 'onEnterFrame'
    function refreshing the flame each time.
    - It's true that I got plenty variables at the _root level.
    If that could be the problem, how can I workaround it?
    - It is my first time trying to embed so many objects at the
    same time too. No idea if the problem could be the way I embed the
    object from the html :(
    - The only thing I can guess is that when a cycle of one of
    the object is running, the other 19 objects must wait their turn.
    That would explain why the more instances I run, the worst results
    I get. In that case, I wonder if there's a way to run them in a
    kind of asynchronous mode, just guessing...
    Any other comment would be appreciated. Anyway, thanks a lot
    everybody for your colaboration.

  • Can I combine multiple threads from the same contact in iMessage?

    iMessage displays multiple threads for the same contact.  Its very confusing and has resulted in lost messages.  I've tried changing a number of settings but to no avail.  Seems to require everyone in my contact list to eliminate all their email addresses in iMessage.
    Begs the question why does iMessage even need this information?  Worse, why does it suck it into its settings by default.  The directory server should only require a valid Apple ID (associated with the users' devices)  in order to direct an iMessage between two contacts.

    Thanks for the reply, appreciate your input.  I did find another way of doing it and that is to highlight the first e-mail, hold down the shift key and click on the last one.  That highlights them all and then they can all be deleted.  Your ideas also work of course and I thank you for that.  Cheers.

  • More than one Thread accessing the same records in the database

    Hi, I have more than one thread accessing a synchronized method called getMinPrimaryKey() which gets the lowest of the primary key frm the table based on the a flag which is set to true. once it is retrieved the same method also sets the flag as false so it is not retrieved the second time. so next time a different thread calls this method it should retrieve the next available lowest primarmy key.
    but even when i have the method as synchronized different threads keep returning the same primary key instead of getting the next sequence. can some one let me know where I might go wrong and what could be the solution. is it because when once i retrieve the record and set the flag as false, i also need to commit it?, which could be the reason the select query still picks up the same primary key. please help me out on this.
    thanks,
    Harish

    Correction. If different threads always return the same key then your table isn't getting up dated. If different threads sometimes return the same key, then either the database is committing lazily, or else the threads are calling getMinPrimaryKey on different objects and so are not executing atomically with respect to each other.

  • Can multiple threads share the same cursor in berkeley db java edition?

    We use berkeley db to store our path computation results. We now have two threads which need to retrieve records from database. Specifically, the first thread accesses the database from the very beginning and read a certain number of records. Then, the second thread needs to access the database and read the rest records starting from the position where the cursor stops in the first thread. But, now, I cannot let these two threads share the same cursor. So, I have to open the database separately in two threads and use individual cursor for each thread. This means I have to in the second thread let the cursor skip the first certain number of records and then read the rest records. However, in this way, it is a waste of time letting the second thread skip a certain of records. It will be ideal for us that the second thread can start reading the record just from the place where the first thread stops. Actually, I have tried using transactional cursor and wanted to let the two threads share the same transactional cursor. But it seems that this didn't work.
    Can anyone give any suggestion? Thank you so much!
    sgao

    If your question is really about using the BDB Java Edition product please post to the JE forum:
    Berkeley DB Java Edition
    If your question is about using the Java API of the BDB (C-based) product, then this is the correct forum.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Multiple User Accessing the same record issue

    I am planning to design an app where we have the following use case requirement.
    If a user who is logged into the system is accessing a record(plan in this case) anyone else who is logged into the system at the same time should be locked out of that same plan but should still be able to access other plans in the system. A plan has many things associated with it so the 2nd user should be locked out of everything associated to the plan being accessed by the first user.
    What is the best way to implement this at the application or the database level?
    Here are some options we have been bouncing around.
    1. When the first user logs in and accesses the first plan we lock the plan at the app level using a singleton class which has one and only one instance on the app server. The plan_id can be put as an entry into a hashtable which can be in the session and is created if one does not exist. When the 2nd user tries to access the same plan, since the plan_id is still in the hashtable he would be locked out. However we somehow need to timeout the first user after 30 mts of inactivity or so so that others can access the plan and are not locked out for ever if the first user walks away from his PC or does not close his browser, thus keeping his session alive indefinitely.
    2. In the database in the plan table we add a column for 'locked'. When the first entry is created in the plan table locked column is marked as 'yes' or 1 and when the user closes the browser we use some javascript to trigger an event which changes that 'yes' or 1 to 'no' or 0 thus unlocking the plan. However the big issue we see in this concept is that we will have to put a javascript onUnload method in all jsp pages in the app because the user could be anywhere in the app after starting his plan access after login.
    Conceptually the 2 options are the same but one is done at the app whereas the other is at the database level.
    Is there a better way to handle this scenario using transactions or some other technological option.
    Thanks

    Another solution involving no modification of the database structure:
    As soon as a user want to access a plan, try to UPDATE the plan record... if it fails, the record was locked
    by another user before. When the user has finished with the plan, you can COMMIT or ROLLBACK the changes, which will free the lock for other users.
    An advantage of this solution is that if program crashes unexpectedly, there will automatically be a ROLLBACK.
    Of course, you need a transaction for this... and perhaps more if you want to separate the 'locking transaction' (virtual update just for restricting access) from the 'operating transaction' (in which you will
    do the DB stuff: inserts, updates, deletes, etc.)
    Hope this helped,
    Regards.

  • Prevent multiple users accessing the same form

    hi,
    i am working in forms
    i have a requirement like this
    if more than one user are using the same form and try to access the same record then the second user should not be able to do transaction
    he should be popped up with a msg saying that other user is working on it
    can any one suggest how to do this in my form
    thanks in advance
    selvaraj s

    That is pretty much exactly the way Forms works automatically.
    Two users can use the same form, and can even display the same data record. One of the users can make changes to the record -- Forms locks the row upon the FIRST keystroke in the first field the user begins to change.
    Once the row is locked, the second user is free to look at the record, and won't even know if another user has begun making changes. However, if second user tries to change even one field in the record, Forms pops up the message, "Could not reserve record (2 tries). Keep trying? Yes / No"
    There are also protections so if the first user actually changes the row and commits, then the second user tries to make a change. Forms will automatically detect whether changes were made, and if so, will undo the change and issue the message, "FRM-40654: Record has been updated by another user. Re-query to see change."
    The above automatic processing works very nicely. If it will not work for you, then what is it you need?

  • Multiple users accessing the same server.

    Ok here is my issue, about 2 months ago I started having issues with Filesharing on my 2012 Mac Mini running Lion server (current update). We have 3 users that VPN into our conpany network and usually access the same folder, 2 months ago they started conflicting with each other. When one VPNs into the network and connects to the server they are fine, if the second one connects to the network they are fine but if the second one tries to access the fileshare they knock the second one off the server. The first one's connection eventually hangs and they have to completely disconnect from the VPN. I am wondering if this was caused by a patch or if there is something else going on. I have tried to reboot the server and checked the logs for anything but I am not seeing what may be causing this. I have restarted the Filesharing in the Server app and still get the same problem, the users are connecting via local credentials to the server. I don't think it is a password issue since either user can log in and access as long as another user doesn't so I am not sure what the issue could be.
    any help appriciated,
    josh

    By 'standard record locking system' do you mean there is nothing I need to do programatically? No block level properties to change?
    So you are saying this is just the way it always works. So as soon as one of our call center agents opens a record all I have to do is create a pending update to any field?
    But won't another user be able to open the form and just query that record not knowing another user has it open?

  • Installing multiple instances accessing the same database

    Hi,
    I want to install two different instances of Oracle 10g in two different machines which will access the same database which will be stored in the shared storage.
    Is it possible to install them without installing RAC? The instances will be one active and the other passive, so the services will be up in one server and down in the other and the switching (shutting down one server and starting up the other) will be manual.
    Two servers will be running Linux and clustered in Linux level.
    Does Oracle offers this solution without installing Clusterware software?
    Thank you

    > The instances will be one active and the other passive, so the services will be up in one server and down in
    the other and the switching (shutting down one server and starting up the other) will be manual
    Missed this part as I was thinking proper cluster and RAC.
    This is neither. Yes, this can be done using two servers and shared storage.
    Is it a good idea? Not really. As this configuration does not provide redundancy at physical database level. You loose that storage.. bye-bye database. Does not matter whether you have a 100 backup servers that can be used.
    Thus the business reasons that you are trying to meet with this config have to be clarified and expectations determined.
    Separate servers using Data Guard will be a far more superior solution in many respects.

  • Multiple users accessing the same data in a global temp table

    I have a global temp table (GTT) defined with 'on commit preserve rows'. This table is accessed via a web page using ASP.NET. The application was designed so that every one that accessed the web page could only see their data in the GTT.
    We have just realized that the GTT doesn't appear to be empty as new web users use the application. I believe it has something to do with how ASP is connecting to the database. I only see one entry in the V$SESSION view even when multiple users are using the web page. I believe this single V$SESSION entry is causing only one GTT to be available at a time. Each user is inserting into / selecting out of the same GTT and their results are wrong.
    I'm the back end Oracle developer at this place and I'm having difficulty translating this issue to the front end ASP team. When this web page is accessed, I need it to start a new session, not reuse an existing session. I want to keep the same connection, but just start a new session... Now I'm losing it.. Like I said, I'm the back end guy and all this web/connection/pooling front end stuff is magic to me.
    The GTT isn't going to work unless we get new sessions. How do we do this?
    Thanks!

    DGS wrote:
    I have a global temp table (GTT) defined with 'on commit preserve rows'. This table is accessed via a web page using ASP.NET. The application was designed so that every one that accessed the web page could only see their data in the GTT.
    We have just realized that the GTT doesn't appear to be empty as new web users use the application. I believe it has something to do with how ASP is connecting to the database. I only see one entry in the V$SESSION view even when multiple users are using the web page. I believe this single V$SESSION entry is causing only one GTT to be available at a time. Each user is inserting into / selecting out of the same GTT and their results are wrong.
    I'm the back end Oracle developer at this place and I'm having difficulty translating this issue to the front end ASP team. When this web page is accessed, I need it to start a new session, not reuse an existing session. I want to keep the same connection, but just start a new session... Now I'm losing it.. Like I said, I'm the back end guy and all this web/connection/pooling front end stuff is magic to me.
    The GTT isn't going to work unless we get new sessions. How do we do this?
    Thanks!You may want to try changing your GTT to 'ON COMMIT DELETE ROWS' and have the .Net app use a transaction object.
    We had a similar problem and I found help in the following thread:
    Re: Global temp table problem w/ODP?
    All the best.

  • What happens when multiple users access the same servlet?

    Do the users share all the same resources? Or is a new process generated for each user? I have a servlet that builds a string to return to the user and I only have myself to test, so I can't really see what happens when many users access the servlet. Is there a possibility that the string will get screwed up, like when dealing with multiple threads, or do all the users get their own resources and I don't have to worry about that?

    huh? if you can point a test servlet at it, you can point a browser at it (even if the servlet does not serve html it will run)
    try pasting the servlet URL into a web browser
    refreshing multiple browsers repeatedly could provide a manual test

  • How can multiple threads hold the same lock?

    I was always under the impression that no 2 threads could hold a lock for the same object, and yet the HotSpot traces say this is happening all the time.
    For example Object 0x0a6c1bf8 is locked in 2 threads:
    "10.129.24.35-1" daemon prio=6 tid=0x2836bad0 nid=0x9d4 runnable [0x2b28f000..0x2b28fc9c]
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    - locked <0x2493f6e0> (a java.net.SocksSocketImpl)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:519)
    at org.jacorb.orb.factory.PortRangeSocketFactory.doCreateSocket(PortRangeSocketFactory.java:142)
    at org.jacorb.orb.factory.AbstractSocketFactory.createSocket(AbstractSocketFactory.java:54)
    at org.jacorb.orb.iiop.ClientIIOPConnection.createSocket(ClientIIOPConnection.java:313)
    at org.jacorb.orb.iiop.ClientIIOPConnection.connect(ClientIIOPConnection.java:160)
    - locked <0x0a6c1b98> (a org.jacorb.orb.iiop.ClientIIOPConnection)
    at org.jacorb.orb.giop.GIOPConnection.sendMessage(GIOPConnection.java:934)
    - locked <0x0a6c1bf8> (a java.lang.Object)
    at org.jacorb.orb.giop.GIOPConnection.sendRequest(GIOPConnection.java:900)
    at org.jacorb.orb.giop.ClientConnection.sendRequest(ClientConnection.java:323)
    at org.jacorb.orb.giop.ClientConnection.sendRequest(ClientConnection.java:304)
    at org.jacorb.orb.Delegate.invoke_internal(Delegate.java:1024)
    - locked <0x0d434a88> (a java.lang.Object)
    at org.jacorb.orb.Delegate.invoke(Delegate.java:939)
    at org.omg.CORBA.portable.ObjectImpl._invoke(ObjectImpl.java:80)
    at com.company.MyApp._StateChangeListenerStub.newChanges(_StateChangeListenerStub.java:33)
    at com.company.MyAppManager.ListenerOneway.send(ListenerOneway.java:65)
    at com.company.MyAppManager.Sender.run(Sender.java:139)
    "ClientMessageReceptor840" daemon prio=6 tid=0x2a3ab988 nid=0x6b4 in Object.wait() [0x2f70f000..0x2f70fb1c]
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:474)
    at org.jacorb.orb.giop.GIOPConnection.waitUntilConnected(GIOPConnection.java:278)
    - locked <0x0a6c1bf8> (a java.lang.Object)
    at org.jacorb.orb.giop.GIOPConnection.getMessage(GIOPConnection.java:318)
    at org.jacorb.orb.giop.GIOPConnection.receiveMessages(GIOPConnection.java:464)
    at org.jacorb.orb.giop.MessageReceptor.doWork(MessageReceptor.java:71)
    at org.jacorb.util.threadpool.ConsumerTie.run(ConsumerTie.java:61)
    at java.lang.Thread.run(Thread.java:595)
    Have I miss-interpreted the HotSpot stack trace?

    To summarise they are both in a synchronized block on the same mutex/Object, but one is in a wait and one isn't.
    So then it follows that if the HotSpot thread reads " - waiting on <address>" like:
    "SomeThread" daemon prio=6 tid=0x29a06658 nid=0xf28 in Object.wait() [0x2b18f000..0x2b18fa1c]
    at java.lang.Object.wait(Native Method)
    - waiting on <address> (a javax.swing.TimerQueue)
    at com.comp.SomeThread.run(TimerQueue.java:236)
    - locked <0x09539510> (a javax.swing.TimerQueue)
    at java.lang.Thread.run(Thread.java:595)
    then it means that the thread is trying to enter the synchronized block on the same mutex/Object but it can't because there is another thread in there which is running, so it is waiting on the outside of the lock instead of the inside of the lock like "ClientMessageReceptor840".
    Ok, I think I get it now. Thanks everyone for your help.

  • Multiple Users accessing the same core set of queried data

    Hi. We have a small call center and we want to build an app where the users can query the same core set of data and use it to initiate calls to study participants. The trick is that they will also need to update each record with information from the call. So we need to stop two call center agents from potentially calling the same participant at the same time.
    Is there a good method or best practice for creating a app to do this? The concern is that multiple call center agents would be querying the screen with the same core set of records (for example, querying by 'Ready for Call' status). When a call is placed the agent will have a conversation with the participant and ultimately end up updating the record after about 10 minutes. So my question is whether there is a good way to keep multiple agents from working with the same record (e.g. calling the same participant simultaneously)?
    Right now it seems that Oracle will lock a record for update, but only after an agent has initiated a change to the record. This still leaves a window of opportunity for two or more agents to be calling the same participant at the same time.
    Any thoughts or ideas on this would be greatly appreciated. Thanks so much.

    By 'standard record locking system' do you mean there is nothing I need to do programatically? No block level properties to change?
    So you are saying this is just the way it always works. So as soon as one of our call center agents opens a record all I have to do is create a pending update to any field?
    But won't another user be able to open the form and just query that record not knowing another user has it open?

  • Multiple classes accessing the same DLL???

    This behaviour is completely unacceptable.
    Let's visualise my app:
    There a 2 java classes:
         ClassA:
              public String[] getPaths(){
                   return getNativePaths();
              public native String[] getNativePaths();
              static{
                   System.loadLibrary("mylib");
              }     ClassB:
              public void setPaths(String[] paths){
                   setNativePaths(paths);
              public native void setNativePaths(String[] paths);
              static{
                   System.loadLibrary("mylib");
              }     MainClass:
              public void testA(){
                   ClassB clsB=new ClassB();
                   String paths[]={"c:\\test.txt"};
                   clsB.setPaths(paths);
              public void testB(){
                   ClassA clsA=new ClassA();
                   String paths[]=clsA.getPaths();
              public void testC(){
                   ClassA clsA=new ClassA();
                   String[] paths=clsA.getPaths();
                   clsA=null;
                   ClassB clsB=new ClassB();
                   clsB.setPaths(paths);
              }Method testA and testB in MainClass don't pose any problems, they work fine. :)
    But when calling testC, I get this:
    java.lang.UnsatisfiedLinkError: no mylib in java.library.path
         at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1403)
         at java.lang.Runtime.loadLibrary0(Runtime.java:788)
         at java.lang.System.loadLibrary(System.java:832)
         ...ClassA and ClassB both work good if used separately (another thread). But if we call one after another (same thread), an exception is thrown.
    So, what's the problem here?
    Is it the return of a string array?

    1 remark:
    If I do this:
        ClassA clsA=new ClassA();
        ClassB clsB=new ClassB();
        clsB.setPaths(clsA.getPaths());This works, but if you call the dll again after this, you'll get the same exception over and over again.
    I think it has something to do with the release of strings (cause there isn't any).
    My native code that returns an array of Strings:
        jobjectArray strArray=null;
        strArray=env->NewObjectArray(nSize,env->FindClass("java/lang/String"),env->NewStringUTF(""));
        // loop
        env->SetObjectArrayElement(strArray,nCount,env->NewStringUTF(dlg->GetNextPathName(pos)));
        nCount++;
        return strArray;

  • Multiple threads on the same applet

    hey,
    i want the following functions should be performed by threads
    *background color of my panel should be changed after the given interval,
    *Label of the panel i.e"HELLO USER" should also blink for the given interval
    *the pictures which i have added on that panel should be shown or hide  for the particular time interval.
    basically i want to know how can i use three threads simultaneously on the same panel.

    Have you tried writing code first or just looking for solution simply...
    You can either create anonymus class or, create a seperate class for Thread or, implement Runnable class
    1. Make Blinking text as component which implements Runnable interface.
    2. Make ImageDisplayer as component which implements Runnable interface.
    3. Make a panel which can change colour as another component which can change color, extent JPanel and implement Runnable interface.
    4. For all the three classes put the logic in run method within a loop and add sleep with required interval (Refer java examples).
    5. Add components to Frame/Applet/Panels and create thread object for them.
    6. Start the thread
    Example:
    Thread blinkingThread = new Thread(...object of runnable interface...)
    blinkingThread.start()

Maybe you are looking for