Thread confusion - synchronized keyword

Hi All,
I am trying to understand when and how to use synchronized. From my tinkering I have come to a situation that is confusing me:
I have an object with two (unsynchronized) methods (called inc and dec). These methods increment and decrement an Integer field called counter. The methods then sleep for a random amount of time.
The contents of the methods are enclosed with a synchronized block, synchronized to the field 'counter'.
I now create two threads, one calling inc the other dec continuously.
From the output the methods are not synchronizing at all.
If I change the synchronized block to sync to a different variable, eg. 'this' or an arbitrary unused object, the code synchronizes properly.
My question/problem is why does the code not synchronize properly on an object that I am altering in the synchronized block.
A second and (hopfully) related question - is:
synchronized public void foo() {...}syntactic sugar for:
public void foo() {
   synchronized (this) {...}
}Thank you for your time in reading this, any help would be very appreciated.
Alex.

Peter-Lawrey - Thankyou!!!
It's obvious now - by creating a new Integer object I am synchronizing on different objects in the two methods, hence still failing to lock the other thread out... DOH!
Here's one of the methods for completeness
     public void inc() {
          synchronized (this) {
               System.out.print("Inc = ");
               try {
                    sleep(1001);
               } catch (InterruptedException e) {
                    e.printStackTrace();
               counter = new Integer(counter.intValue() + 1);
               System.out.println(counter.toString());
     } As Integers are readonly I have to intValue, then increment then create a new Integer Object.
Out of curiosity - does the synchronized block fail at this point or does is now apply to the new object until the end of the block is reached?
Thankyou again for your help and returning a small part of my sanity!
Alex.

Similar Messages

  • Terminating enqueued threads at synchronized block

    Hi!
    I would really appreciate your opinions: :)
    The application desing:
    - I'm developing a web applicaction running on a Tomcat server.
    - The app is being developed using Struts and Spring.
    - Pages (presentation layer) are made of JSPs.
    - There are Spring beans (Services) that execute the business logic.
    - These Services are used by the Struts Actions.
    My problem case:
    1. When you submit myPage.jsp, MyAction.java's execute method is called.
    2. MyAction.java uses MyService.java's "process()" method to do some file processing that takes 2 to 3 hours to finish.
    3. This MyService.java is a singleton Spring bean.
    4. The call to process() method is synchronized on MyAction.java like this:
    public ActionForward execute(...) throws Exception {
         // Some code ...
         synchronized (this) {
              myService.process(...); // This method takes up to 3 hours to return
              // Some code ...
         return mapping.findForward("success");
    }As you can imagine, many requests (threads) will be enqueued at the synchronized keyword line. Because of this, I need to provide a cancelation functionality. This would be fired by a cancel button on myPage.jsp.
    So, if you tried to launch the so-long-process by the "Process" button on myPage.jsp and you received a "Waiting..." message at your screen (because the 3 hours process was launched by another client), you should be able to cancel your processing request (because you don't want to wait so much time to begin your file processing).
    I would really appreciate your opinions on which would be the best approach to achive this cancelation functionality.
    I'm sure there's a better way than the one I came up with: I could populate a class variable Map with "sessionId - Thread" (key - value) everytime a request arrives at the line before the synchronized block. Thus, when you clicked the Cancel button, MyAction.java would get the request's session id and then get the Thread it must terminate from the Map. Having the Thread instance, I could maybe call it's interrupt method.
    I don't think that's the best approach, but it's the only one I could thought about.
    Thank you very much for your time and opinions!

    Well, first thing I'd say is that if you use Spring, you'd be better off using it's own Controller architecture which is, to my mind, a lot more developed than Struts, especially now you can do pretty much the whole thing with @RequestMapping rather than XML.
    Having a web transaction wait for a long running server action is basically a bad idea. Rather you should have the web front end launch the file processing job and return immediately, probably showing a list of jobs to the user which may be queued, running or finished (for good or ill). One technique is to display a "background action in progress" page which submits a new transaction every few minutes to check if the job has finished yet (using a Javascript timer). If the job is still queued or running then this request displays the "in progress" page again, if finished it displays the result.
    Such a page could have a "Stop" button to abort the running job if feasible.
    I would suggest that you have a queue of background jobs, probably serviced by a ThreadPoolExecuter. The initial request simply builds a request object and queues it.
    Use a ContextListener object to create the queue and start the executer when the application starts, and close it down when the application is stopped,

  • Synchronized keyword for simple addition

    Hi, I have a function, as given below
    {noformat}public static void increment() {{noformat}{noformat} a = a + 1; {noformat}{noformat}}
    {noformat}
    This function will be called from multiple threads (a is also a static variable).
    My question is should I use "synchronized" keyword for this method to avoid unpredictable results? Is there a way to wirte this function without using "synchronized" keyword?
    Please suggest.

    Thanks, jwenting. I wanted to confirm that "synchronized" has to be used.
    jwenting wrote:
    yes. Depending of course on what you decide to be "unpredictable" :)you understand what "unpredictable" means here ;)
    jwenting wrote:
    yes, don't use a static variable but a method local one. Of course that will have a totally different effect.Variable "a" should be a class level variable. Yes, local variable has a totally different effect. ;)

  • Understanding 'synchronized' keyword

    Hello,
    I have a main class (ClsA.java) that extends JFrame, the frame contains one JButton and one JTextArea.
    When pressing the button x number of threads are created and each thread will write a couple of messages in the JTextArea by using a method in ClsA.java, the method looks like this:
    public void output(String output){
      this.taOutput.append(new java.util.Date(System.currentTimeMillis()) + ":" + output + System.getProperty("line.separator"));
    }everything works fine, but sometimes a few messages from different threads end up on the same line in the JTextArea. To fix this I changed the output method to this:
    public synchronized void output(String output){
      this.taOutput.append(new java.util.Date(System.currentTimeMillis()) + ":" + output + System.getProperty("line.separator"));
    }I have just added the synchronized keyword that will make the the system associates a unique lock with every instance of ClsA (there is only one). This works alomost fine, but when I increase the number of concurrent threads the application freezes(I�m not able to scroll down in the textarea or press the button)? Why does it freeze? I have tried adding notifyAll() at the end of the output method but there is no difference. What am I doing wrong here? The acquisition and release of a lock is done automatically and atomically by the Java runtime system.....but can it still end up in a freeze?!
    Greatfull for any suggestions!
    //Anders =)

    Hi,
    Use
    public void output(String output){
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    taOutput.append(new java.util.Date(System.currentTimeMillis()) + ":" + output + System.getProperty("line.separator"));
    so as to update the text area only in the event thread!
    Roger

  • 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]

  • 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

  • How can see the effect of synchronized keyword

    hi
    I read the follwoing code in some books:
    class W{
    static private int count=0;
    public String name;
    int no;
    private static synchronized int addW(){    return ++count; }
    public W(){ no= addW();  }
    }but I think that synchronized keyword in this code doesn't have an effect, i.e., if we remove it, the output would be ok, can anyone able to change this code such that the output becomes different depend on existance of synchronized keyword.
    thank you

    but I think that synchronized keyword in this code
    doesn't have an effect, i.e., if we remove it, the
    output would be ok,Well, you're mistaken.
    can anyone able to change this
    code such that the output becomes different depend on
    existance of synchronized keyword.No change is necessary. Synchronization is required to ensure proper behavior for the code presented.

  • Implementing method and add 'synchronized' keyword

    Basically, I have the following scenario:
    public interface ClassA {
      public void doSomething(String s);
    } Then, the class that implements ClassA:
    public class ClassB implements ClassA {
      public ClassB() {
        doSomething("Testing");
      public synchronized void doSomething(String s) {
        // Do something...
      public static void main(String[] args) {
        ClassB cb = new ClassB();
    }ClassB implements the doSomething(String s) method but adds the 'synchronized' keyword. I compile this and get no errors, but I wanted to make sure that adding the 'synchronized' keyword to a method that is implemented is a legit thing to do.
    The reason I am asking is that Rational Rose does not generate code for this situation correctly, and before I call tech support, I wanted to make sure that it is not a problem with what I am doing. When Rose generates the code, it gives a warning that the method doSomething was not implemented and it adds the method. I then have two methods called 'doSomething'.
    Thanks

    'synchronized' is not part of the method signature. But if you want to work around the problem, instead of declaring the method as synchronized, simply do this instead, which is equivalent (for non-static methods):
    public void doSomething(String s) {
      synchronized (this) {
        // your code here

  • 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

  • Question about using threads and synchronizing objects

    Hi all,
    I am not that familiar and I have 2 questions.
    QUESTION 1
    I have a server which just sits and accepts incomming connections, then I spawn off a new thread which implements Runnable, and then call the run method. But the loop would not iterate, it would just sit inside the run method (which has rather long loop in it). I changed the class to extend Thread and called the start() method, rather than run(), and everything worked out fine.
    Anyone know why this is?
    QUESTION 2
    So I am building a client server chat application where a user can be in multiple chat rooms. I have this personObject which has output/input streams. In the personObject, I create writeObject/ readObject method, which simply does as it implies.
    I figured that I should make these methods synchronized, to ensure things run smoothly. however, when I made a call to readObject, which sat there and waited, and then made a call to writeObject, I would not enter the writeObject method. I took out the synchronized on the writeObject, and everything worked out fine.
    I was under the assumption that synchronizing a method only synchronized on that method, not on the whole class. How come then was I not able to enter the writeObject method?
    The more I think about it, I don't think I need to have these methods synchronized, but I thought it wouldn't hurt.
    Thanks for the help.

    Hi all,
    I am not that familiar and I have 2 questions.
    QUESTION 1
    I have a server which just sits and accepts incomming
    connections, then I spawn off a new thread which
    implements Runnable, and then call the run method.
    But the loop would not iterate, it would just sit
    inside the run method (which has rather long loop in
    it). I changed the class to extend Thread and called
    the start() method, rather than run(), and everything
    worked out fine.
    Anyone know why this is?
    You should still implement Runnable, rather than extending Thread. Like this: Runnable r = new MyRunnable();
    Thread t = new Thread(r);
    t.start(); run() is just another method. Nothing special about it as far as multithreading or anything else goes.
    start() is the method that actually spawns a new thread of execution.
    I was under the assumption that synchronizing a
    method only synchronized on that method, not on the
    whole class. How come then was I not able to enter
    the writeObject method?When you synchronize, you obtain a lock. As long as you hold that lock--until you exit the sync block or call wait()--no other thread can enter that block or any other block that obtains the same lock.
    Two synchronized methods on the same object rely on obtaining the same lock--there's one lock for each object.

  • How to use Synchronized Keyword

    Hi guys,
    Sorry if this is a simple question, but I'm not sure about the following:
    Suppose we have the class,
    Class Foo
    public synchronized void bar1() {...}
    public synchronized void bar2() {...}
    If I have two threads running concurrently, say T1 and T2.
    I know that T1 and T2 can't both be in bar1() at the same time right? [It has to be in some serial order]
    But, can T1 be in bar1() and T2 be in bar2() at the same time?
    I guess the question is, does the synchronized apply to that specific method only? Or rather to the object (which basically limits at most one thread calling that object's synchronized methods)?
    Thanks a bunch! :)
    -Michael.

    Hi Michael,
    In general, when you syncronize a block of code, the execution of the block is syncronized ON an object. Any object can function as a lock, and only one thread can have a lock of one object at a time. If one thread already has a lock on an object and another thread tries to acquire lock on the same object, the latter thread will wait until the lock is released.
    When you use 'synchronized' in method declaration, it means that the execution of the whole method is syncronized on the object itself (NOT class, if the method is non-static. Static method would be synchronized on the .class object.)
    So, if you have more than one syncronized methods, only one of them is executed at a time ON THE SAME OBJECT. The same method can, of course, be executed simultaneously on other objects. Also, if some of the methods are synchronized, but other methods are not, the non-synchronized methods are not affected in any way.
    It might be good to note that these two pieces of code have exactly the same meaning:
    public synchronized doSomething() {
        // do something
    }and
    public doSomething() {
        synchronized (this) {
            // do something
    }Hope this helps.
    Cheers,
    Vesa
    p.s. It's a good idea to design your code so that one thread will have no more than one lock at a time. If it's possible for more than one thread to have lock on more than one object, there may be a risk of the threads dead-locking, which will crash any program...

  • Thread Confusion

    Good day to all.
    In my application I have to make some calls to the network which can take some time to execute. My object creates a pool of 5 worker threads to execute the network calls.
    In my testing it launches the first 5 and has to sleep while it waits for the first launched to come back and be available again. It seems that when the main Thread sleeps it causes the worker threads to sleep as well. Is this supposed to happen? Could it be because the worker Threads are inner classes of the main thread?
    Thanks for any advice.

    I appreciate the help. I'm mentally stuck. I'll post the whole thing but first I'll try to sum up what I am trying to do. I may have an idea of what's happening but I'm not sure.
    Many client objects are trying to post DNS lookups.
    A single object contains a hashtable of queries that have been performed.
    I want any user to get an immediate response from the object so that others can make a query.
    The code....
    package com.PCM.SnifferMessageTools;
    Created 6/28/2004 Praise the Lord!
    The DNS Lookup factory will be a utility module.
    This utility module will be instantiated with a name.
    The name is the DNS source.  After that the operation
    will be the same for all objects.  There will be X number of
    singleton objects based on the names.
    The action is to go to the source and ask DNS information
    about a particular ip address.  A caller will ask for the
    information.  If the information is available
    an immediate response is given.  If it's not available
    a thread is displatched to get the information.
    All information will be returned as an object.  This makes each
    response seemingly immediate even though an individual
    may have to wait for his / her answer.
    public class DNSLookupFactory {
      // Here is where we store the singleton
      // instances.
      private static java.util.Hashtable singletons = new java.util.Hashtable();
      // Each instance will have a hashtable that contains
      // the responses for a query.
      private java.util.Hashtable responses = new java.util.Hashtable();
      // There will be a maximum number of threads that
      // will be allowed to go out for information.
      int MAX_THREADS = 5;
      // And this is where they will be stored.
      Thread[] workers = new Thread[MAX_THREADS];
      // And the current thread is
      private int CURRENT_THREAD = 0;
      // If a thread has not completed we will need to
      // wait a number of times and for a period of time.
      private final long sleeptime = 1000;
      private final int MAX_WAITS = 5;
      // We all need a name, don't we?
      // In this case the name will be
      // something.org.
      // This is a handy way to create
      //[ reverseip.something.org ]
      private String factoryName;
      private DNSLookupFactory(String factoryName){
        this.factoryName = factoryName;
      public static synchronized DNSLookupFactory getinstance(String name){
        // If one has not been created, create one.
        Object obj = singletons.get(name);
        if(obj == null){
          obj = new DNSLookupFactory(name);
          singletons.put(name,obj);
        return (DNSLookupFactory)obj;
      // A thread will obtain a result of some kind.
      // That data will be stored in the
      // responses hashtable.  To make this work we
      // have to make sure that only one thread can
      // post a job and post information at a time.
      // This will be done with an object as a place holder.
      class DNSResponse{
        boolean complete = false;
        boolean result = false;
      // This method may get additional query info
      // just a stub for now.
      private synchronized void lookup(String ip) throws Exception{
        if(responses.get(ip) == null){
          // no query has been called yet so we
          // post.....
          responses.put(ip,new DNSResponse());
          // And launch the thread to get the information.
          // This is where people will have to
          // wait and get in line if too many queries
          // are in progress.
          if(CURRENT_THREAD >= MAX_THREADS) CURRENT_THREAD = 0;
          // Now we will wait and see if the thread is done yet.
          Mercury M = (Mercury)workers[CURRENT_THREAD];
          // If there is no thread there we will initialize one.
          if(M != null){
            System.out.println("Calling " + M.name);
            int count = 0;
            while(!M.completed){
              Thread.currentThread().sleep(sleeptime);
              count++;
              if(count > MAX_WAITS) throw new Exception("Waited too long for thread.");
          // If I am here th thread is completed and I can start
          // a new one.
          workers[CURRENT_THREAD] = new Mercury(ip,this);
          workers[CURRENT_THREAD++].start();
      private synchronized void post(String name, String data) throws Exception{
        // make sure that no other thread has posted this info.
        // That shouldn't happen so if it has
        // we will throw an exception.
        DNSResponse D = (DNSResponse)responses.get(name);
        if(D == null) throw new Exception("Error. Thread returned to empty house.");
        if(D.complete) throw new Exception("Error.  Thread returned to full house.");
        // Otherwise post the information.
        D.complete = true;
        D.result = new Boolean(data).booleanValue();
      class Mercury extends Thread{
        boolean completed = false;
        String name;
        DNSLookupFactory factory;
        public Mercury(String name,DNSLookupFactory factory){
          this.name = name;
          this.factory = factory;
        public void run(){
          // go and get data and post it.
          // If there is an exception we have to throw it as
          // a runtime exception.
          try{
            String url = buildReverseIP(name);
            String result = String.valueOf(new DNSNetLookup().doA(url));
            System.out.println("Result from " + name + " " + result);
            factory.post(name,result);
            System.out.println(name + " posted.");
            completed = true;
          }catch(Exception e){
            completed = true;
            throw new java.lang.RuntimeException(e);
          System.out.println(name + " completed");
      // This is what people will get when they ask for information.
      // they will get an object (representative) that asks for them.
      // This is so that all takers will get a fast response.
      // Some may have to wait for the specific information
      // but all will get a fast response.  It's a way of getting
      // static performance form an instance object.
      class Representative{
        private String name;
        public Representative(String name) throws Exception{
          this.name = name;
          // Now we go to our mothership and post the query.
          lookup(name);
        public boolean getResponse() throws Exception{
          // Here is where this user may have to wait.
          // We will let this spin until the answer is ready.
          DNSResponse D = (DNSResponse)responses.get(name);
          while(!D.complete){
            Thread.sleep(sleeptime);
          return D.result;
      public Representative query(String ip) throws Exception{
        // A representative is built based on teh name and returned.
        return new Representative(ip);
      private String buildReverseIP(String ip){
        java.util.StringTokenizer ST = new java.util.StringTokenizer(ip,".");
        String[] tmp = new String[ST.countTokens()];
        int count = tmp.length - 1;
        while(ST.hasMoreTokens()){
          tmp[count--] = ST.nextToken();
        StringBuffer buffer = new StringBuffer();
        for(int a = 0; a < tmp.length; a++){
          buffer.append(tmp[a]).append(".");
        return buffer.append(factoryName).toString();
    }Thanks again

  • Synchronized keyword was not supposed to be reentrant ?

    Synchronized block in the below code seems to be working properly as a reentrant code. I've written this to check out the reentrancy by causing a deadlock but it worked without deadlock./* This code might cause to a deadlock */
    public class NotReentrant {
         public static void main(String[] args) {
              final LoggingWidget widget = new LoggingWidget();
              Thread t1 = new Thread(new Runnable() {
                   public void run() { widget.execute(); }
              t1.start();
              try { t1.join(); } catch (Exception e) {}
              System.out.println("You might not going to see this: There is a deadlock !");
    /* dummy classes that show the proof */
    class Widget {
         public synchronized void execute() {
              System.out.println(toString() + " (base).execute: synchronized");
              synchronized (this) {
                   System.out.println(toString() + " (base).execute: synchronized (this)");
                   try { Thread.sleep(500); } catch (Exception e) {}
                   System.out.println(toString() + " (base).execute");
                   // .... code
    class LoggingWidget extends Widget {
         public synchronized void execute() {
              System.out.println(toString() + ".execute: synchronized");
              super.execute();
              System.out.println(toString() + ".execute");
    }

    I perfectly understand how Java monitors work and I also perfectly know that Java synchronized ( aka intrinsic locks ) monitor is re-entrant.
    The reason behind my previous post was that I am trying to check out a code which is written in Goetz's book: Java Concurreny in Practice. In there, he gives a code example that leads to a deadlock. Despite, I am aware of the fact that it cannot be occurred, I have given it a shot.
    Thanks for the comments.

  • Who is the expert with Synchronized keyword?

    I have searched this forum regarding how synchronized behaves, and have found many posts with conflicting information.
    I have a servlet that calls a separate synchronized method from within the doGet method.
    What I want to know is: when one thread is executing the synchronized method, will other threads still be able to run doGet concurrently, as long as they do not need to invoke the synchronized method?
    Or when one thread enters the synchronized method, will all other threads stop what they are doing if they are already executing doGet, until the other thread is finished with it?
    I don't see how synchronized can lock an entire class, when 2 threads already may be executing within the class.

    No, the sychonized block or method only affects thos ho actually need to acquire the same monitor. Other threads of control invoking doGet() but who don't need to concurrently call mySynchronizedMethod() will NOT be blocked or disturbed in any way.
    Of course two threads of control could enter mySynchronizedMethod() concurrently if they are called against a separate instance of your servlet and the method is not static. This may be correct behavior.
    Oh, and how could there be two instances of your servlet? Well the container is in control of that. Generally speaking there would be a single one unless your servlet implements SingleThreadModel in which case the container usually maintains a pool of some (usually configurable) size of instances of your servlet and chooses one for each request coming in to its service() method.
    Chuck

  • Best position of  "synchronized" keyword?

    Hi, I have a fairly straightforward question: which one is better/more performant:
    synchronized (dirLock) {
      try {
        FileUtils.forceMkdir(dir);
      } catch (IOException e) {
        throw new Exception("Could not create storage directory!", e);
    }or
    try {
      synchronized (dirLock) {
        FileUtils.forceMkdir(dir);
    } catch (IOException e) {
      throw new Exception("Could not create storage directory!", e);
    }I.e. is it better to wrap the entire try/catch block in a synchronized block, or just the operation I care about?
    Thanks in advance,
    Maarten

    In your example it hardly matters, but in general it is better to synchronize as little as possible, therefore
    I prefer your second example. I would use it even with your code, just for consistency.
    try {
      synchronized (dirLock) {
        FileUtils.forceMkdir(dir);
    } catch (IOException e) {
      ... do stuff...
      ... do more stuff....
      throw new Exception("Could not create storage directory!", e);
    }

Maybe you are looking for

  • A non-modal, but "always on top" JDialog

    Hi everyone, In an applet I am creating, I need to create a non-modal JDialog which stays on top whenever its open. The reason this JDialog is required to be non-modal is that I need the main applet window to be able to react to events and reflect ch

  • Muse update to allow for hi-res images on Retina displays?

    I understand that you can find a javascript file for static images, but I am looking to for better image quality on buttons as well since my navigation utilizes imagery. Does any one know if Adobe is addressing this issue? Any work-arounds in the mea

  • Just bought an .OTF font for Flash CS6 and it's not showing up in the list.

    Just bought an .OTF font for Flash CS6 and it's not showing up in the list. EscrowText-Roman.otf Any reason why? It shows up in Illustrator and Photoshop just fine. Line

  • Problems with Lightroom 5 downloading, installing,

    Wedownloaded and installed lightroom 5 for teacher's and students but when we try to run it we get a screen that says we need to extract the files, then when it does so it takes us back to the screen that says we need to extract the files. We don't s

  • Itunes memory hog with classic ipod?

    Itunes is using 1 GB plus when connected to my ipod classic using Win7.  Takes for - ever to manually manage music. Any ideas on how to speed it up?