Use of 'synchronized'

Hello,
Is there any difference (other than having to declare a lock object in the second case) between :
public void synchronized myMethod(){
doSomething();
and
public void myMethod() {
synchronized(lock) {
doSomething();
Thank you.
Benoit

it is not only a difference in performance, but one
version is threadsafe on multiprocessor machines and
the other is not.
[snip]
The reasoning is that the synchronized keyword on a
method is handled by the jvm as a special case and has
the capability to do the locking between processors(if
it's a good jvm). The synchronized block as was
stated produces byte code (2 of them). Because of
this, the jvm can't do this additional optimization
because it cannot possibly lock both processes without
the chance of deadlock since each process can be
trying to lock each other after the first byte code,
but before it finishes the second. So therefore the
jvm must purposely not synchronize the multiple
processes.Interesting argument, but it doesn't seem to sit right.
Taken directly from the JVMS, the two instructions will roughly be...   2  aload_2      // Push local variable 2 (f)
   3  monitorenter // Enter the monitor associated with fhttp://java.sun.com/docs/books/vmspec/2nd-edition/html/Compiling.doc.html#6530
There is no possibility of deadlock by interleaving any combination of the above two bytecodes, since the monitorenter is defined as a cpu-atomic operation. From the JLS (emphasis added)...
http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html#28287
For the purposes of this chapter, the verbs use, assign, load, store, lock, and unlock name actions that a thread can perform. The verbs read, write, lock, and unlock name actions that the main memory subsystem can perform. Each of these actions is atomic (indivisible).
I read this as saying that the monitorenter instructions can be assumed to execute serially, since they are atomic operations on the shared memory. Therefore, the second CPU to execute the monitorenter instruction will find the monitor taken, and will wait for it to be released.
This of course assumes that the two processors share a single memory... else this breaks down to a distributed JVM problem, which will need extra semantics to conform to the JLS and JVMS.
If you have any links to information on the thread-safe behaviour of java on multi-processor systems, they would be greatly appreciated - the specification means to me that both constructs should be thread-safe, but if there is anecdotal evidence to the contrary...
Regards,
-Troy
PS- There were no reported bugs to this effect that I found in Sun's java bug database

Similar Messages

  • Use of Synchronized  in jsp/servlet

    Can any one explain me the use of Synchronized in servlet/jsp which is multithreaded Is this correct synchronized should be used only when we want to pritect Static variable as they have only one copy but in case of instance variable they have seperate copy for each instance so no point of synchronized.
    Thanks in advance

    Hello again,
    Take an external file for instance, you open a input stream to it and read data from it in your Java application. You can't have two threads reading at the same time, and one will likely block or throw an exception.
    A better example is when your threads need to communicate with each other. If they all communicate via a set of variables that can be read and written to by any of them, then they should be synchronized. You should know if your threads need to communicate with each other? If they do not, there is no need for synchronisation.
    What are your threads doing if you don't mind me asking?
    I have to admit, I have had little experience using threads, and I have never needed to use threads in JSP (I don ot directly use servlets).
    Regards,
    Darren

  • I am unable to get a bullited list when using the synchronized text feature.

    I am unable to get a bullited list when using the synchronized text feature. The option is greyed out and not active. Any tips? Am I doing something wrong?

    This is by default , synchronized text does not alter any style and other visual attributes associated with instance.
    Thanks,
    Sanjit

  • Trouble with executing RTP using fnd_transaction.synchronous

    Background: We have an existing PL/SQL program executed via a concurrent program that processes RECEIVE type receipts. This program inserts RECEIVE type records into the RCV_TRANSACTIONS_INTERFACE table for further processing by executing the Receiving Transactions Processor in a subsequent concurrent program stage. All receive receipts are currently processed in batch mode with the RTP.
    We are now trying to implement three way match. Part of the process involves handling RETURN TO VENDOR and CORRECT type receipts. Unfortunately, according to 360340.1 on Oracle Support, return to vendor is a two step process (at least for us). I've noted that simultaneously inserting the RETURN TO RECEIVING and RETURN TO VENDOR receipt records into the RCV_TRANSACTIONS_INTERFACE table and having the RTP process both these records in one fell swoop does NOT work. It errors out and I get the following error in PO_INTERFACE_ERRORS:
    The Quantity entered for receipt is greater than the available Quantity. The sum of quantity to be received and already received, 10, is greater than the sum of ordered quantity and over receipt tolerance, 0.
    Interestingly, a return to vendor receipt works if I insert the RETURN TO RECEIVING record first, then run the RTP, then insert the RETURN TO VENDOR record, then run the RTP. Thus, I need separate executions of the RTP in order for this to work. Can someone tell me if I can do this with one execution of the RTP batch mode? Would I have something wrong in the RETURN TO RECEIVING and RETURN TO VENDOR records in the RCV_TRANSACTIONS_INTERFACE table? I know this has to be a two step return process (RETURN TO RECEIVING and RETURN TO VENDOR), but I'm wondering why I can't just execute the RTP once - why do I have to execute it twice?
    If I have to execute the RTP twice, then it leads me to the question addressed in the subject of this message. My current design is I would like to execute the RTP via fnd_transaction.synchronous after each record is inserted into the RCV_TRANACTIONS_INTERFACE table. I've tried executing the RTP via fnd_transaction.synchronous after the insert of RETURN TO RECEIVING and RETURN TO VENDOR, but it does not work for me. In fact, I've tried executing the RTP via fnd_transaction.synchronous after the insert of a receive transaction (RECEIVE) just for testing - and it does not work. I've turned on debugging and I see an ORA-1403 error in the fnd_concurrent_debug_info table:
    ORA-01403: no data found
    I've used some info from the following page:
    http://karthikrajasekaran.blogspot.com/2009/12/receiving-transaction-processor.html
    I've set the apps context, too... So I'm not sure what's going on. Does anyone have an idea?

    Check the below query, I think this might help.
    select okhb.contract_number contract_number
    ,msi.segment1 line_item
    ,msi.description line_item_description
    ,msi_sub.segment1 sub_line_item
    ,msi_sub.description sub_line_item_description
    from
    okc_k_headers_b okhb
    ,okc_k_lines_b oklb
    ,okc_k_items oki
    ,mtl_system_items_b msi
    ,okc_k_lines_b sub_ln
    ,okc_k_items sub_items
    ,csi_item_instances cii
    ,mtl_system_items_b msi_sub
    where
    okhb.contract_number = 'NK20269112'
    and okhb.contract_number_modifier = '1 yr'
    and okhb.id = oklb.chr_id
    and oklb.id = oki.cle_id
    and oki.jtot_object1_code = 'OKX_SERVICE'
    and oki.object1_id1 = msi.inventory_item_id
    and oki.object1_id2 = msi.organization_id
    and oklb.id = sub_ln.cle_id
    and sub_ln.lse_id IN (7, 8, 9, 10, 11, 18, 25, 35)
    and sub_ln.id = sub_items.cle_id
    and sub_items.jtot_object1_code = 'OKX_CUSTPROD'
    and sub_items.object1_id1 = cii.instance_id
    and sub_items.object1_id2 = '#'
    and cii.inventory_item_id = msi_sub.inventory_item_id
    and cii.inv_master_organization_id = msi_sub.organization_id

  • Help SOAP to RFC Scenario using BPM (Synchronous communication)

    Hi,
    I am doing a scenario from SOAP to RFC scenario(Synchronous communication).  Here I am creating a PM Notification in the SAP system through a webservice. 
    I am using three BAPI'S here,
    1. BAPI_ALM_NOTIF_CREATE 
    2. BAPI_ALM_NOTIF_SAVE
    3. BAPI_TRANSACTION_COMMIT
    I am successful in calling the first BAPI from the Web Service.  For this I have not used BPM.  But to commit the transaction(PM notification in this case), I have to execute the other two BAPI's as well.  I have to pass the output of first BAPI to the second BAPI and then execute the 2nd BAPI.  And finally have to execute the 3rd BAPI.     FYI, 3rd BAPI is not dependent on any output.  It has to be executed independently after execution of the first two BAPI's.
    How can I execute this scenario?  Do I have  to use BPM?  If yes please let me know the steps in detail.  I have not done any BPM scenario till now.  So please answer me in detail.
    Thanks in Advance,
    Vijay
    p.s. reward points are must

    Hi Vijay,
    Yes, You will indeed need a BPM in this case...
    Based on my understanding of the Scenario u have explained, here are the steps that would be needed.
    1. Receive With the Sync-Async Bridge open.
    2. Transformation Step (Between the source Request and The BAPI_ALM_NOTIF_CREATE Request)
    3. Send Synchronous
    4. Fork
    5. In one Branch of the fork - Transformation (Between the BAPI_ALM_NOTIF_CREATE Response and API_ALM_NOTIF_SAVE Request)
    6. In the other branch of the fork - Transformation (Between a Dummy Source and the BAPI_TRANSACTION_COMMIT Request)
    7. Send Synchronous (to make the 2nd BAPI Call)
    6. Transformation ( BAPI_ALM_NOTIF_SAVE Response and the source Response)
    7. Send Asynchronous (to make the 3rd BAPI call)
    8. Send the Source Response and close the Sync-Async Bridge.
    There might be alternative ways also of doing it...
    Also a better design would be to take care of the 2nd and the 3rd BAPI call within the code of the 1st RFC Function Module.
    Regards,
    Abhy Thomas

  • Correlation used with synchronous steps in BPM

    Hello,
    we have a problem with a correlation.
    A receiver step synchronous activates a correlation.
    The step is completed by receiving a response.
    The receiver step connects via sRFC to an R/3 system to trigger there an IDOC.
    Next step of the BPM is to receive the IDOC from the R/3 system (async).
    This system uses the correlation (time stamp field from RFC).
    But: This doesn not work.
    We only had success when using an asynchronous RFC.
    Does anybody have experience with such issues?
    What is possibly wrong with our correlation ?
    (Corr. is local within a block where both steps are included, RFC and IDOC step)
    regards
    Dirk

    Here is a little twist to the correlation issue...
    I had the following problem. I have a very simple Sync/Async bridge, including a sync. reveiver (sr) at the beginning, as closing S/A bridge sender (ss) at the end, and a async. sender (as) and an async. receiver (ar) in the middle. My messages have an orderId that I use for my correlation.
    The first receiver (sr) activates the correclation (using the orderId in the request message).
    I then attempted to "use correlation" in my async. receiver (ar) step. The correlation shows up in the drop down options in the properties window of the step, but my selection would not "stick" (it would show it and revert to the red question mark).
    After checking my correlation and unsuccessfully trying a few permutations of where to "activate" the correlation, I tried this:
    I temporarily turned my synchronous steps into asynchronous steps (sr and ss). Then I selected my correlation in the async. receive step and it "stuck". After my selection was accepted in the "use correlation" property of the async. receiver step, I turned my first and last step (sr and ss) back in to synchronous steps and had the desired result.
    ... and it worked! I guess it is just a little bug in the tool (which may not be an issue in later releases?!)
    Marc
    (FYI, I am using XI 3.0 SP 16)

  • Use of synchronized in constructor for accessing static SimpleDateFormat

    Just a little confused. I have
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
    in my class. I made dateFormat static final, because its a costly operation that I dont want to do more than once. I access dateFormat in the constructor of my class to format a date. Since SimpleDateFormat is not threadsafe, my understanding is the access has to happen in synchronized block to ensure thread-safety, as follows
    public MyClass (date) {
    synchronized(dateFormat) {
    dateFormat.format(new Date());
    Is that right? I know that constructors dont need to be synchronized because they are object creations, hence cant have multiple threads stepping on one another. But since dateFormat is a static field, doesnt it need to be protected, inspite of the above argument? Would appreciate responses/comments. Thanks

    this constructor constructs a log record and uses the dateformatter to add timestamp to the log. It is executed very frequently. My tests indicate that using a static dateformatter is better performing than using a new formatter per thread. I am including the results below. 'u method' stands for unsynchronized (new formatter for each thread) and 's method' for synchronized (with static formatter)
    run completed, took [ 10] milliseconds to format date, using 'u method' for [ 1] threads
    run completed, took [ 0] milliseconds to format date, using 's' method for [ 1] threads
    run completed, took [ 10] milliseconds to format date, using 'u method' for [ 10] threads
    run completed, took [ 0] milliseconds to format date, using 's' method for [ 10] threads
    run completed, took [ 40] milliseconds to format date, using 'u method' for [ 50] threads
    run completed, took [ 30] milliseconds to format date, using 's' method for [ 50] threads
    run completed, took [ 70] milliseconds to format date, using 'u method' for [ 100] threads
    run completed, took [ 40] milliseconds to format date, using 's' method for [ 100] threads
    run completed, took [ 260] milliseconds to format date, using 'u method' for [ 500] threads
    run completed, took [ 170] milliseconds to format date, using 's' method for [ 500] threads
    run completed, took [ 491] milliseconds to format date, using 'u method' for [ 1000] threads
    run completed, took [ 310] milliseconds to format date, using 's' method for [ 1000] threads
    run completed, took [ 1793] milliseconds to format date, using 'u method' for [ 5000] threads
    run completed, took [ 1472] milliseconds to format date, using 's' method for [ 5000] threads
    run completed, took [ 3164] milliseconds to format date, using 'u method' for [ 10000] threads
    run completed, took [ 2524] milliseconds to format date, using 's' method for [ 10000] threads
    run completed, took [ 14571] milliseconds to format date, using 'u method' for [ 50000] threads
    run completed, took [ 12819] milliseconds to format date, using 's' method for [ 50000] threads
    run completed, took [ 28050] milliseconds to format date, using 'u method' for [ 100000] threads
    run completed, took [ 25107] milliseconds to format date, using 's' method for [ 100000] threads

  • Use of synchronized keyword with portal services

    Hi,
    Can you confirm me if it is true that a portal service is a Singleton? I mean, when using an instance variable of a portal service I am able to set the value of the instance variable using one client app and get it afterwards using another client app. So we are talking about the same and only instance of the portal service, right?
    If this is true how can I synchronize the access to a portal's service method? I tried to mark
    the method syncronized (in the interface) but then I realized that this issues a compiler error because one can not mark an interface method synchronized. So can I mark the implementation class instead? That is, can I leave the interface without the synchronized keyword for the method and still mark the implementation of the method in the service class as syncronized? Does this work?
    Thanks in advance,
    Diz

    Hi,
    Portal service is not a Singleton, as the name says a service is just provider for services which does not save state between two requests/applications.
    So if you want to save state, then use some session variables to save it.
    In a cluster installation, each server node has its own portal services, so if you save state in service, then your application should save this state on all servers of the cluster.
    So you should change your approch.
    http://help.sap.com/saphelp_nw70/helpdata/en/e3/fab74247e2b611e10000000a155106/frameset.htm
    Greetings,
    Praveen Gudapati
    [Points are always welcome for helpful answers]

  • Use of Synchronized Keyword / Concurrency

    I have a program which makes two Writer threads (they add 1 to a shared
    counter), A sampler Thread (like a reader thread � it also displays the
    data held by the other thread). I have been playing around with the
    synchronised keyword � but I am not sure how to interpret the
    results..I'll post the code first....
    the shared counter------------------------------
    package sycTest;
    public class Counter
    {public int val = 0;}
    the sampler / reader class----------------------
    package sycTest;
    public class Sampler extends Thread
    private Counter c;
    private MyThread A, B;
    public Sampler ( MyThread A, MyThread B, Counter c ) {
    this.A = A;
    this.B = B;
    this.c = c;
    public void run()
    while(true)
    try { sleep( 1000 ); } catch (Exception x) { }
    System.out.println
    "A count = " + A.getCount() + ", " +
    "B count = " + B.getCount() + ": " +
    "A + B count = " + (A.getCount() + B.getCount()) + ", " +
    "shared counter = " + c.val
    the main class to get things started------------------------------------
    package sycTest;
    import java.util.Random;
    public class Main
    public static void main( String[] args )
    Counter c = new Counter();
    MyThread A = new MyThread( c );
    MyThread B = new MyThread( c );
    A.start(); B.start();
    // create and start Sampler thread in one step
    new Sampler( A, B, c ).start();
    // main thread waits to read a carriage-return.
    try {
         System.in.read();
    catch( Exception e ) { }
    System.exit(0);
    /* rand_sleep function is used to generate "random switching" behaviour
    assuming n > 0,
    rand_sleep( n ) sleeps a random time between 0 and n millisec.
    private static Random rand = new Random();
    public static void rand_sleep( int maxms ) {
    int ms = rand.nextInt() % maxms; // - maxms < ms < maxms
    int amt=(ms + maxms + 1)/2;
    try { Thread.sleep(amt); } catch(Exception e) { }
    the thread / writer class-------------------------------------------
    package sycTest;
    public class MyThread extends Thread
    private Counter sharedCounter;
    public MyThread( Counter c ) { this.sharedCounter=c; }
    private int count=0;
    public int getCount() { return count; }
    public void run() {
    while(true)
              // simulate non-critical section by sleeping a "large" amount
              Main.rand_sleep(1000);
              synchronized (sharedCounter) {
              criticalSection();
              //Main.rand_sleep(1000);
              ++count;
    private void criticalSection() {
    int x=sharedCounter.val + 1;
    Main.rand_sleep( 100 );
    sharedCounter.val=x;
    --the question!
    The idea is that running the main methods gives something like
    A count=13, B count=10: A + B count=23, shared counter=23
    (where A and B are writer threads)
    If I take out the synchronised keyword in the MyThread class, things get
    much worse...the 'personal' totals of A and B do not equal the total
    held in the shared counter rather quickly..
              criticalSection();
              //Main.rand_sleep(1000);
              ++count;
    eg
    A count=13, B count=10: A + B count=23, shared counter=22
    However, adding the synchronised keyword (eclipse suggested
    �sharedCounter� as the argument � the notes seem to suggest �this�, but
    if I do that the synchronised keyword seems much like the example above...
    synchronized (sharedCounter) {
              criticalSection();
              ++count;
    this makes it much better...I never saw it get the counts 'wrong'
    eg
    A count=56, B count=72: A + B count=128, shared counter=128
    Now comes the confusing bit...when I add some time between the 2 methods
    within the sychonized block...
    synchronized (sharedCounter) {
              criticalSection();
              Main.rand_sleep(1000);
              ++count;
    Then mismatches appear very quickly, the program behaves very similarly
    to when it didn't have the synchronised keyword...
    Why is this? Is it because the Sampler class is asking what the values
    of the shared and personal counters during the �Main.rand sleep(1000)�
    call??
    The other question I was hoping someone could help me with, is pointing
    out what the difference is between �synchronized (sharedCounter)� and
    �synchronized (this)� is in this context. Why does the later not do
    anything in this example?
    Thanks,
    Julian

    Hello Julian,
    you're Sampler thread reads the different counters without any synchronization. He may call A.getCount() and get 5 back, then yield and then ask for c.val which was increased by A in the meantime. Or A increases it's own counter, then yields and lets the Sampler output nonsense.. ;)
    To clear up the confusion surrounding Thread.sleep(long): It would be a waste to do nothing while the thread is sleeping, so another thread gets to play. Since the other MyThread is waiting on sharedCounter's monitor and the sleeping thread still owns it<sup>1</sup> the Sampler thread gets the execution time. Now the sampler gets going and you know the rest.
    1: http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.9
    EDIT: In future, use code-tags:
    class MyClass {
        private int myField;
    }will turn into
    class MyClass {
        private int myField;
    }With kind regards
    Ben
    Edited by: BenSchulz on Mar 24, 2008 11:45 AM

  • Use of synchronized queue for java socket communications

    Hi all,
    We have a need for a server socket application (stand alone java application) to process just one command per time coming from a java socket client (JSP Web application). There are a lot of users accessing the java socket client, but the server socket can only handle one command per time, so there is a need of a queue type, so users will have to wait for their time.
    We've been told that we can use "synchronized Queue", but we don't know what it is and how to use. A URL, book etc. with sample code would assist us, since we are new to both java socket communication and queue of commands.
    Can anyone assist us
    cheers
    Trajano
    P.S.
    The server socket java application has two threads:
    1st thread handles the java socket communication;
    2nd thread is a RS-232 serial driver that communicates to several micro-controllers connected on a multi-drop.
    JSP web app client socket users can issue various commands at the same time to the java server socket app, however the server can only service one command per time (just one RS-232 COM1 serial port available). The commands have to somehow be added to a queue for processing.

    I do not have the experience to offer advice. But I just happened to be reading today about Collections.synchronizedList.
    import java.util.List;
    import java.util.LinkedList;
    import java.util.Collections;
    public class Queue {
       private List queue;
       public Queue() {
          queue = Collections.synchronizedList(new LinkedList());
       public Object removeItem() throws InterruptedException {
          synchronized (queue) {
             while (queue.isEmpty())
                queue.wait();
             return queue.remove(0);
       public void addItem(Object item) {
          synchronized (queue) {
             queue.add(item);
             queue.notifyAll();
    class Test {
       public static void main(String[] args) {
          final Queue queue = new Queue();
          //start a thread to process items from the queue
          Runnable work = new Runnable() {
             public void run() {
                try {
                   Object item = queue.removeItem();
                   //do something with item
                } catch (InterruptedException e) {
                   //handle this
          Thread worker = new Thread(work);
          worker.start();
    }Reference: Java Thread Programming, Paule Hyde
    Also, here is Doug Lea's library,
    http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html

  • How to use "Start synchronous Call" to run a subVi and keep timeout event in Main vi still running?

    Hi, All
    I have a application need periodically check an instrument status and I put it in the "Timeout Event" in main vi. I also need call some subVis for configuration etc. Somehow when I called those subvi, the Timeout event in my main vi was not running. Then I use " Start Asynchronous Call" function to call the subVis. Turns out it works fine with some subvis without return value, but not as expected with "return value-needed" subvis. 
    I attached a simple test, my main vi call two dlg subvis: AboutDlg.vi and SettingsDlg.vi. In the timeout event, I just use a counter for simulation. When you run it, you can see the counter keep counting when the AboutDlg.vi was called, but stopped when SettingsDlg.vi was called. 
    As I remembered, someone suggested to use Queue to pass return value, but I don't know how to implement it here. 
    Anyone has any suggestions about it? 
    Thank you very much. 
    CQ
    Solved!
    Go to Solution.
    Attachments:
    AsyCallTest.llb ‏108 KB

    Try playing with this - I have modified  your code to poke a Q in there.
    You will want to change the clusters to more useful datatypes (maybe enum and variant so you can unbundle variants depending on enum input), you will want to type def the clusters to make it easier to maintain and you will NEED to handle the sitaution where the called VI is left open on program close - i couldn't be bothered as this was not your immediate issue)
    Hope this give you some Ideas - totalyy untested but should work.
    James
    Attachments:
    AsyCallTest.llb ‏114 KB

  • Using and synchronizing applications from Windows Server 2012 on local desktop

    I have Visual Studio 2010 on my remote server.  How do I use Visual Studio  software from the server on my local laptop and sync it with the server?

    Of course remote desktop assumes that the system is also properly licensed for Remote Desktop Connections.
    A little clarification on the OP's request might also be in order.
    "How do I use Visual Studio  software from the server on my local laptop and sync it with the server?"
     If you want to run VS on the server, using something like remote desktop services, it runs there and the data stays there.  Obviously you can redirect where VS will store data so that it stores data on your laptop, but then there is nothing to
    automatically synchronize it.  Maybe a more complete explanation of your issue would help.
    . : | : . : | : . tim

  • Issue with service entry sheet creation using synchronous service

    Hi,
      I am using a synchronous service inside that i am calling bapi bapi_entrysheet_create with testrun
    set,so that commit doesnot happen inside the bapi,then outside i am explicitly calling commit work.
    Still database table is not updated,commit is not working.

    Hi Venu,
       But I cannot set test run as initial because if testrun is set to initial bapi_entrysheet_create logic
    is written in such a way that it calls commit work inside the bapi....and so we cannot rollback later
    in the synchronous service.
    Regards,
    Tess

  • Use of 'static' keyword in synchronized methods. Does it ease concurrency?

    Friends,
    I have a query regarding the use of 'synchronized' keyword in a programme. This is mainly to check if there's any difference in the use of 'static' keyword for synchronized methods. By default we cannot call two synchronized methods from a programme at the same time. For example, in 'Program1', I am calling two methods, 'display()' and 'update()' both of them are synchronized and the flow is first, 'display()' is called and only when display method exits, it calls the 'update()' method.
    But, things seem different, when I added 'static' keyword for 'update()' method as can be seen from 'Program2'. Here, instead of waiting for 'display()' method to finish, 'update()' method is called during the execution of 'display()' method. You can check the output to see the difference.
    Does it mean, 'static' keyword has anything to do with synchronizaton?
    Appreciate your valuable comments.
    1. Program1
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    end display:
    start update:
    end update:
    2. Program2
    package camel.java.thread;
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    start update:end update:
    end display:

    the synchronized method obtain the lock from the current instance while static synchronized method obtain the lock from the class
    Below is some code for u to have better understanding
    package facado.collab;
    public class TestSync {
         public synchronized void add() {
              System.out.println("TestSync.add()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.add() - end");          
         public synchronized void update() {
              System.out.println("TestSync.update()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.update() - end");          
         public static synchronized void staticAdd() {
              System.out.println("TestSync.staticAdd()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticAdd() - end");
         public static synchronized void staticUpdate() {
              System.out.println("TestSync.staticUpdate()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticUpdate() - end");
         public static void main(String[] args) {
              final TestSync sync1 = new TestSync();
              final TestSync sync2 = new TestSync();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.add();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.update();
              }).start();
              try {
                   Thread.sleep(3000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.staticAdd();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.staticUpdate();
              }).start();
    }

  • Object or Statement Block locking using synchronized keyword in java

    Hi ,
    Can anyone tell me how java is implementing the Object locking and the code block locking mechanism using the 'synchronized' keyword internally??
    Thanks in advance
    Raj

    The JVM implements a concept known as a monitor using a combination of direct implementation and support by the operating system. For more detail, refer to the Java JVM and language specifications.
    Chuck

Maybe you are looking for

  • Replacing places.sqlite with older file is not working, please help I need my bookmarks

    My hard drive was recently crashed so I had to reinstall windows 7 operating system. I recovered the deleted places.sqlite file from before the crash. I replaced the old file with new places.sqlite file but is not restoring any of the bookmarks Pleas

  • Files or Folders needed for blu-ray disc missing !

    Hi, I have Encore CS6. It successfully builds 'blu-ray folder' & 'blu-ray image' without any error. But when I try to create an iso image of the prepared folder using 'Ashampoo Burning Studio' it gives an error message saying that the folder doesn't

  • Problems with date in procedure on Oracle 11g

    Hi gurus, I have some problems with the date format on Oracle 11g. Let me explain the situation: When I am starting a request like select to_number(to_char(to_date('01.04.2009','dd.mm.yyyy'), 'yyyy')) from sys.dual I got as result 2009 as number. Whe

  • I am trying to recover a 4s which is diabled

    This is driving me NUTS, I am trying to recover a 4s which is disabled and the screen has the msg. "wait 23,477,878 minutes" Is someone having a laugh? Also , when trying to recover. I get the error "can't proceed phone locked" in itunes. As I write

  • Wireless internet..​.help!

    okay, so go easy on me, i am totally new to the black berry thing.  i got a curve 8300 when someone was too lazy to fix their cracked plastic screen.  i hate my old phone, so, i took this one.  i haven't switch any of my features over with at and t,