Dont understand Synchronized method to complete program

I'm trying to finish theis program but i don't understand synchronized methods. I checked the java tutorial and i am still confused. Can someone help me approach finishing this program. Here is the spec and the first part of the program i have done.
===================================================================================
When the above is working, create a class called Food. The objective here is to demonstrate the behavior of threads that share data, and use synchronized methods.
Simulating an animal eating, simply means that the thread will sleep for some length of time.
There is one instance of the Food class that is shared by both of the animals. Pass it to the constructor of the Animal class.
There is a method in the Food class called eat(). This method is synchronized, i.e., only one Animal can be eating at a time.
The rabbit eats the food (the thread will sleep) for a longer time than the turtle, thus giving an advantage to the rabbit.
But, the turtle must wait until the rabbit is done eating until it can eat, so the advantage is reduced. Print out a message in the eat method when the animal begins to eat, and when it is done eating. Indicate which animal it is that starts to eat.
Try making the eat method not synchronized, and observe the different behavior if the eat method allows the rabbit to begin eating before the turtle is done eating
   import java.util.Random;
    public class Animal extends Thread implements Runnable{
      private String name;
      private int position;
      private int speed;
      private int restMax;
      public static boolean winner = false;
      Random random = new Random();
       public Animal (String name, int position, int speed,int restMax){
         this.name = name;
         this.position = position;
         this.speed = speed;
         this.restMax = restMax;
       public void run(){
         try{
            while( winner == false){
               if(position < 100){
                  Thread.sleep(random.nextInt(restMax));
                  position += speed ;
                  System.out.println(name+" is in "+ position+" position ");
               if (position >= 100){
                  winner = true;
                  System.out.println(name+" is the winner");
                  System.exit(0);
             catch(InterruptedException e){
       public static void main(String[] args){
         Animal rabbit = new Animal("trix", 0, 5, 150);
         Animal turtle = new Animal("maury",0, 3, 100);
         rabbit.start();
         turtle.start();
   }

Example:class Donkeyphile implements Runnable {       
    private Donkey donkey;
    private long time;
    Donkeyphile(Donkey donkey, long time) {
        this.donkey = donkey;
        this.time = time;
    public void run() {
        for (int i = 0; i < 10; i++) {
            donkey.love(time);
    public static void main(String[] args) {
        Donkey donkey = new Donkey();
        Donkeyphile jverd = new Donkeyphile(donkey, 500);
        Donkeyphile yawmark = new Donkeyphile(donkey, 100);
        Thread j = new Thread(jverd, "Jverd");
        Thread y = new Thread(yawmark, "Yawmark");
        j.start();
        y.start();
class Donkey {
    synchronized void love(long time) {
        String name = Thread.currentThread().getName();
        System.out.println(name + " hugs the donkey.");
        try { Thread.sleep(time); } catch (InterruptedException e) { }
        System.out.println(name + " releases the donkey.");
}

Similar Messages

  • HT1925 When I try to uninstall apple updater I get a message that says " The feature you are trying to use is on a network resource that is unavailable." I dont understand this. How can I finish uninstalling the apple update program?

    When I try to uninstall apple updater I get a message that says " The feature you are trying to use is on a network resource that is unavailable." I dont understand this. How can I finish uninstalling the apple update program?

    (1) Download the Windows Installer CleanUp utility installer file (msicuu2.exe) from the following Major Geeks page (use one of the links under the "DOWNLOAD LOCATIONS" thingy on the Major Geeks page):
    http://majorgeeks.com/download.php?det=4459
    (2) Doubleclick the msicuu2.exe file and follow the prompts to install the Windows Installer CleanUp utility. (If you're on a Windows Vista or Windows 7 system and you get a Code 800A0046 error message when doubleclicking the msicuu2.exe file, try instead right-clicking on the msicuu2.exe file and selecting "Run as administrator".)
    (3) In your Start menu click All Programs and then click Windows Install Clean Up. The Windows Installer CleanUp utility window appears, listing software that is currently installed on your computer.
    (4) In the list of programs that appears in CleanUp, select any Apple Software Update entries and click "Remove", as per the following screenshot:
    (5) Quit out of CleanUp, restart the PC and try another iTunes install using an iTunesSetup.exe (or iTunes64Setup.exe) downloaded from the Apple Website:
    http://www.apple.com/itunes/download/
    Does it go through properly this time?

  • Need Help! Passing an array of objects to a method, dont understand

    Hi, i need to make a method called public Server[] getServers() and i need to be able to see if specific server is available for use.
    I have this so far:
    public abstract class AbstractServer
    protected String serverName;
    protected String serverLocation;
    public AbstractServer(String name,String location)
    this.serverName=name;
    this.serverLocation=location;
    public abstract class Server extends AbstractServer
    public Server(String name,String location)
    super(name,location);
    public class CreateServers
    Server server[];
    public CreateServers()
    public Server create()
    for(int i=0; i<10; i++)
    server=new Server(" ", " "); //i was going to fill in something here
    return server;
    OK NOW HERE IS THE PROBLEM
    i have another class that is supposed to manage all these servers, and i dont understand how to do the public Server[] getServers(), this is what i have tried so far
    public class ServerManager()
    public Server[] getServers(Server[] AbstractServer)
    Server server=null; //ok im also confused about what to do here
    return server;
    in the end i need this because i have a thread class that runs the servers that has a call this like:
    ServerManager.getServers("serverName", null);
    Im just really confused because i need to get a specific server by name but i have to go through AbstractServer class to get it
    Any help?

    thanks for replying...
    ok ill remove the Server.java one to be
    public class Server extends AbstractServer
         public Resource(String name,String locaton)
              super(name,location);
    ok so inside ServerManager.java i should have something like
    ArrayList servers;
    public ServerManager()
    servers=new ArrayList();
    ok but i still dont get how to use that in a method
    say if i put it like this
    public getServers()
    //populate server list in here??????
    ok im still lost...

  • I am trying to download a plug in called adobe flash player 10.1.102 and error shows up that says instalation encountered errors sign in under administraive privileges and try again and i dont understand what that is or what to do. help please!

    im tryin to down load this plugin like it keeps suggesting because none of the video clips or games of any sort is showing and it wont download. it keeps saying theres an error and i need to sign in under administrative privileges but it doesnt give me that option. i dont understand what to do> help please!!!

    Follow the instructions below. Note the part about "Windows 7 and Vista".
    #'''Check your plugin versions''': http://www.mozilla.com/en-US/plugincheck/
    #*'''Note: plugin check page does not have information on all plugin versions'''
    #'''Update the [[Managing the Flash plugin|Flash]] plugin''' to the latest version.
    #*Download and SAVE to your Desktop so you can find the installer later
    #*If you do not have the current version, click on the "Player Download Center" link on the "Download..." page below
    #*After download is complete, exit Firefox
    #*Click on the installer you just downloaded and install
    #**Windows 7 and Vista: may need to right-click the installer and choose "Run as Administrator"
    #*Start Firefox and check your version again or test the installation by going back to the download link below
    #*Download and information: http://www.adobe.com/software/flash/about/
    #**Use Firefox to go to the above site to update the Firefox plugin (will also install plugin for most other browsers; except IE)
    #**Use IE to go to the above site to update the IE ActiveX
    <br />
    The information submitted with your question indicates that you have out of date plugins with known security and stability issues that should be updated. To see the plugins submitted with your question, click "More system details..." to the right of your original question post.
    *Adobe Shockwave for Director Netscape plug-in, version 11.0
    *Adobe PDF Plug-In For Firefox and Netscape
    **New Adobe Reader X (version 10) with Protected Mode just released 2010-11-19
    **See: http://www.securityweek.com/adobe-releases-acrobat-reader-x-protected-mode
    #'''Check your plugin versions''': http://www.mozilla.com/en-US/plugincheck/
    #*'''Note: plugin check page does not have information on all plugin versions'''
    #'''Update Shockwave for Director'''
    #*NOTE: this is not the same as Shockwave Flash; this installs the Shockwave Player.
    #*Use Firefox to download and SAVE the installer to your hard drive from the link in the article below (Desktop is a good place so you can find it).
    #*When the download is complete, exit Firefox (File > Exit)
    #*locate and double-click in the installer you just downloaded, let the install complete.
    #*Restart Firefox and check your plugins again.
    #*'''<u>Download link and more information</u>''': http://support.mozilla.com/en-US/kb/Using+the+Shockwave+plugin+with+Firefox
    #'''Update Adobe Reader (PDF plugin):'''
    #*From within your existing Adobe Reader ('''<u>if you have it already installed</u>'''):
    #**Open the Adobe Reader program from your Programs list
    #**Click Help > Check for Updates
    #**Follow the prompts for updating
    #**If this method works for you, skip the "Download complete installer" section below and proceed to "After the installation" below
    #*Download complete installer ('''if you do <u>NOT</u> have Adobe Reader installed'''):
    #**Use the links below to avoid getting the troublesome "getplus" Adobe Download Manager and other "extras" you may not want
    #**Use Firefox to download and SAVE the installer to your hard drive from the appropriate link below
    #**Click "Save to File"; save to your Desktop (so you can find it)
    #**After download completes, close Firefox
    #**Click the installer you just downloaded and allow the install to continue
    #***Note: Vista and Win7 users may need to right-click the installer and choose "Run as Administrator"
    #**'''<u>Download link</u>''': ftp://ftp.adobe.com/pub/adobe/reader/
    #***Choose your OS
    #***Choose the latest #.x version (example 9.x, for version 9)
    #***Choose the highest number version listed
    #****NOTE: 10.x is the new Adobe Reader X (Windows and Mac only as of this posting)
    #***Choose your language
    #***Download the file
    #***Windows: choose the .exe file; Mac: choose the .dmg file
    #*Using either of the links below will force you to install the "getPlus" Adobe Download Manager. Also be sure to uncheck the McAfee Scanner if you do not want the link forcibly installed on your desktop
    #**''<u>Also see Download link</u>''': http://get.adobe.com/reader/otherversions/
    #**Also see: https://support.mozilla.com/en-US/kb/Using+the+Adobe+Reader+plugin+with+Firefox (do not use the link on this page for downloading; you may get the troublesome "getplus" Adobe Download Manager (Adobe DLM) and other "extras")
    #*After the installation, start Firefox and check your version again.

  • Which object's monitor does a synchronized method acquire?

    from the Java Tutorial for concurrency programming:
    " When a thread invokes a synchronized method, it automatically acquires the intrinsic lock _for that method's object_ and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception. "
    what exactly does this mean?
    do synchronized methods acquire the monitors for objects of type: java.lang.reflection.Method
    please consider this code:
    public class Foo {
      private int counter = 0;
      public synchronized void incriment() { counter++; }
      public synchronized void decriment() { counter--; }
    Foo f = new Foo();
    Class[] sig = new Class[0];
    Method m = f.getClass().getMethod("incriment", sig);
    // ok. so "m" is the relevant method object.
    f.incriment(); // <-- is the monitor for "m" ,
                          // or the monitor for "f", acquired?
    .......my reading of the Concurrency Tutorial is that synchronized methods use the monitors of java.lang.reflection.Method objects?
    and thus, Foo is not thread safe, right?
    however, this simple change makes Foo thread-safe?
    public class Foo {
      private volatile int counter = 0; // "volatile"
      public void incriment() { counter++; }
      public void decriment() { counter--; }
    }thanks.
    Edited by: kogose on Feb 23, 2009 7:13 PM

    tensorfield wrote:
    jverd wrote:
    tensorfield wrote:
    kogose wrote:
    what exactly does this mean?It means you're complicating things.
    If a method is synchronized, it is. You don't need to go beyond that. The method is synchronized.Not true. You have to know what it means for a method to be synchronized. Often people come in with the erroneous impression that it somehow prevents you from using or accessing the object in any other thread.It's very simple. If a synchronized method is called at the same time from many threads only one call will be executed at a time. The calls will be lined up and performed one after the other in sequence.
    AND because synchronization is on a per object basis, when one synchronized method is being called from one thread, all synchronized methods of that same object are blocked for calling from other threads.
    Simple as that.No, it's not that simple, and as stated, that is not correct. In particular, you didn't mention that for an instance method, all the various threads have to be trying to call instance methods on the same object in order for execution to be sequential.
    You really can't understand Java's syncing without understanding how it relates to locks, and what it means for a method to be synchronized in terms of which lock it acquires.
    Edited by: jverd on Feb 25, 2009 2:47 PM

  • I dont understand creating classes they seem a waste of time and efficiency

    I dont understand why we would want to create classes with constructors and get and set statements... I know that VB and Java did not create these just to have us writing extra code so I am missing something in my thinking.
    I read about data hiding and that I understand I guess...but everytime my professors want me to create a class then create an object from that class to access it I dont really get it. I know how to do the basics of it but I can do all of it in my main or the primary class whats the benefit of creating a whole entire class such as the following?
    Everytime I get an assignment and they are like create a class and I try to rack my head for a good idea but the nearest analogy I can come up with is this... creating your own class seems like one of those old straws you drink out of with all the loops, yes you can make it go around in a big loop but why waste time? you want to get to point A to point B so create the most efficient way to get there if possible.
    I am sure the problem is I am not seeing something and there is some logic missing but I just am getting irritated as I am not seeing it and I am finding it, its like I add an extra obstacle course to my code for no other reason than to run through a bunch of extra tasks that I could perform in my main class or main.
    input is welcome to help me arrive at some type of enlightenment thanks
    Class may not be the correct wording for this as I know we have to have a class but what I mean is a non application class. The class I have below goes with another class that actually does a lot of stuff but I am forced to push data through this class that basically does nothing but run water through some different pipes if you will. To me thats a waste when I can do everything in my original class which was called menu that I am messing with and that creates an array for a user who wants to keep a list of his items and prices of those items in inventory.
    public class Item
    private String itemName;
    private double itemPrice;
              public Item()
    public Item (String item, double price)
    setName(item);
    setPrice(price);
    public String getName()
         return itemName;
    public void setName(String item)
         itemName = item;
    public double getPrice()
         return itemPrice;
    public void setPrice(double price)
         itemPrice= price;
    Edited by: Bricatw on Oct 30, 2009 10:33 PM

    What I was plugging into it and please forgive the code as its not finished... (I am still messing with it) its just for learning and I am required to have certain parts in the Item Class and Certain parts in the Menu class..... But you it pushes through the input to the java bean.... in a case like this I just dont see the need for doing it not that I can think of anyway.
    import java.util.Scanner;//my imports for scanner so can read from the screen
    import java.util.*;//imports for my array I used astrix to just import it all as the book said it does not have any negative affects.
    public class Menu //My application class Menu that contains my main
         public static void main(String[] args)//Main method
              final int NUMBER_Of_Elements = 30; //created a symbolic constant so that I only have to change the constant
              //to edit the size of the array if I should want to change it.
              Item[]inventory = new Item[NUMBER_Of_Elements];//I create a new array object with the constant as the number of elements.
              Scanner sc = new Scanner (System.in);//created object from the scanner class used to get input from the console screen.
              System.out.println("Please enter Item on first line and price on second line.");//outputted text to prompt user and give instructions.
              System.out.println("Enter STOP to exit");//instructions on how to exit the program. I would have rather used a different
              //word than stop here. If my choice I would have used "exit" as its more widely used and to promote uniformity.
              int count;//count variable used to count my loops very important as we use it to control our arrays and loops here.
              double price;//our variable that we plug in values from the user via the console.
              String item;//same as previously mentioned for the "price"
                        System.out.println("Wings Coffee Shop Menu");
              System.out.println("");
              System.out.println("Menu Item Price");
              for (count=0; count<inventory.length; ++count)//This is our for loop it uses the length method to control how many times
              //it runs. In this case inventory.length = 30 elements so would run 30 times unless it stopped early.
                   item = sc.nextLine();//reads the input from console into the item variable.
                   if(item.equalsIgnoreCase("STOP"))//if statement that states if = stop (ignores case sensitivity) then it will break out of the loop.
                   break;//the break command which is executed if the if statement is true.
                   price = Double.parseDouble(sc.nextLine());//
                   inventory[count]= new Item(item, price);
                   Item Call = new Item(item, price);
                   System.out.printf("%-13s %.2f\n", Call.getName(), Call.getPrice());
              System.out.println("Wings Coffee Shop Menu");
              System.out.println("");
              System.out.println("Menu Item Price");
    //           for(int x = 0; x < count; ++x)
    //           System.out.printf("%15s\n",inventory[x].toString());
    //                System.out.printf("%-13s %.2f\n", Call.getName(), Call.getPrice());
    //           String[] namesOfItems = {"Coffee", "Milk", "Soda", "Bagel", "Croissant", "Donut"};
    //           double[] prices = {3.99, 2.99, 2.49, 2.99, 2.49, 1.99};
    //           for(int x = 0; x < prices.length; ++x)
    //           System.out.printf("%-13s %.2f\n", namesOfItems[x], prices[x]);
    //           Item arrayPrice = new Item(); HOW COME I CANNOT CREATE THIS OBJECT?
    //           Item call = new Item ();
    //           Item Call = new Item("item", 4.9);
    Edited by: Bricatw on Oct 30, 2009 11:22 PM

  • What is this code? I dont understand it

    Hi I need to loop my hole program but i dont understand this solution that someone gave me on the forum...
    public static void main(String[] sgra) {
    do {
    stuff();
    while(askUserWhetherToContinue());
    }

    It's a do-while loop. With misplaced braces, it should be
    do {
        stuff();
    } while (askUserWhetherToContinue());as your compiler is probably telling you.
    This pretty much does what it says; the part inside the "do" is repeated until the part within the "while" equals false. If your main looks like above, you would put whatever your program is supposed to do in a method "stuff", and you would query the user to e.g. press y/n in the "askUser" method and return their answer as a boolean.

  • Problem in synchronized methods

    i have two synchronized methods.One methods displays a JFrame.It has a button jButton1.the other method just return boolean true.
    these two methods are called by another class which has more methods.What i need is to run stop processing in parent class methods untill jButton1 is clicked.Can i use synchronizing for this?
    Regards
    Udayani
    public synchronized void go() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {                                      
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
    e.printStackTrace();
    this.getContentPane().setLayout(null);
    jPanel1.setLayout(null);
    read();
    int i=0;
    while(i<fno){
    jCheckBox=new JCheckBox();
    jCheckBox[i].setText(Files[i].getParent()+"\\"+Files[i].getName());
    System.out.println(i);
    jCheckBox[i].setBounds(new Rectangle(10,30+i*30, 200, 23));
    jPanel1.add(jCheckBox[i], null);
    i++;
    jPanel1.setBounds(new Rectangle(0, 0, 350,100+fno*30));
    this.setSize(new Dimension(350, 100+fno*30));
         this.setTitle("Selected Files");
    this.setVisible(true);
    jButton2.addActionListener(new selectedFiles_jButton2_actionAdapter(this));
    this.getContentPane().add(jPanel1, null);
    jButton1.setBounds(new Rectangle(165, 30 + fno * 30, 75, 25));
    jButton1.setFont(new java.awt.Font("Dialog", 1, 12));
    jButton1.setMargin(new Insets(2, 13, 2, 14));
    jButton1.setText("Yes");
    jLabel1.setFont(new java.awt.Font("Dialog", 1, 12));
    j Label1.setText("Add more files");
    jLabel1.setBounds(new Rectangle(30, 35 + fno * 30, 154, 15));
    jButton2.setBounds(new Rectangle(233, 30 + fno * 30, 75, 25));
    jButton2.setFont(new java.awt.Font("Dialog", 1, 12));
    jButton2.setMaximumSize(new Dimension(73, 25));
    jButton2.setMargin(new Insets(2, 13, 2, 14));
    jButton2.setText("No");
    jPanel1.add(jLabel1, null);
    jPanel1.add(jButton1, null);
    jPanel1.add(jButton2, null);
    repaint();
    done=true;

    if you don't use threads, you don't need "synchronized" all it does is slowing down your code, without any other effects.
    Either you go into threads completely (yes, it is a non-trivial topic that requires some work) or you better leave it. Simply calling methods "synchronized" has no effect on your single-threaded program.

  • DWR manual ....something i dont understand

    MANUAL :
    http://getahead.ltd.uk/dwr/examples/text
    few relevant lines of code from this link and from browser's view-source ...
    HTML code :
    <script type='text/javascript' src='/dwr-demo/dwr/engine.js'> </script>
    <script type='text/javascript' src='/dwr-demo/dwr/util.js'> </script>
    <script type='text/javascript' src='/sitefiles/getahead/generic.js'> </script>
    <script type='text/javascript'>
    function update()
        Demo.getServerInfo(loadinfo); // line -1
    function loadinfo(data)  // line -2
        DWRUtil.setValue("reply", data);
    <h2>Demo</h2>
    <p>Query Server: <input value="Execute" type="button" onclick="update()"/>
    <br/>Server Information: <span id="reply" style="background:#eeffdd; padding-left:4px; padding-right:4px;"></span></p>IN THE SERVER we Have
    public String getServerInfo()
    return ExecutionContext.get().getServletContext().getServerInfo()
    + " running on JDK "
    + System.getProperty("java.specification.version")
    + " using DWR "
    + ExecutionContext.get().getVersion();
    QUESTION :
    i dont understand how the //line-1 and //line-2 works. feeling very much uncomfortable to adopt this syntax.
    // line-1 and //line-2 are uncomfortable ...how they are calling each other. a function getServerInfo() is taking a loadinfo function as a parameter. and loadinfo(data) is the function body !
    this is confusing.
    can anybody have any comment on this ?

    One day, everyone will realize that javascript has nothing to do with Java. But until then...
    This javascript code and HTML markup is fairly simple and fairly common in style. Line -1 invokes the Demo.getServerInfo() method and passes it a reference to a function that it is to use to process the returned information. Somewhere in the implementation you would see that the passed-in function is invoked with an actual value parameter that represents the data received (I suppose) and corresponds to the formal parameter 'data' found at line 1. The idiom in use here is that of 'passing a reference to a callback function' and is common across many languages.
    So, why not just have getServerInfo() return the data and let the caller call line -2? Well, the most obvious reason is that this is supposed to be asynchronous and therefore the caller doesn't (in fact cannot) block until the Demo.getServerInfo() completes.
    Not sure if that answered your question...

  • Optimizing synchronized method?

    A couple of other threads got me to thinking about a bit of code I commonly use. Is a synchronized method really expensive enough to make this modification warranted?
    Original method:
      private static Manager theManager = null;
      public static synchronized getManager() {
        if (theManager != null) return theManager;
        theManager = new Manager();
        return theManager;
      }Optimized version:
      private static Manager theManager = null;
      public static getManager() {
        if (theManager != null) return theManager;
        synchronized (theManager) {
          if (theManager != null) return theManager;
          theManager = new Manager();
        return theManager;
      }The intent is that since theManager gets created only rarely (i.e. once at the beginning of the session) all the subsequent invocations do not need to execute the synchronized logic. Is this worth it?

    The article states that the use of the volatile keyword fixes the problem, at least for later versions Java. Is that not right?For JDK 1.5 and above, perhaps. For JDK 1.4 and below, no.
    However, I am more interested in the solution presented by a link elsewhere in that article:
    http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom
    That method solves the problem and no synchronized keyword is needed at all.That's true. However, follow the [double-checked locking|http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html] link in that article, to actually understand what's going on. And pay particular attention to the part that says For most applications, the cost of simply making the getHelper() method synchronized is not high. You should only consider this kind of detailed optimizations if you know that it is causing a substantial overhead for an application.
    And finally: you do realize that singleton is almost never necessary, introduces tight coupling into your program, and makes it difficult to test. Right?

  • Intrinsic locks - static synchronized method

    I am trying to understand the "static synchronized threads" - by theory when such a thread is invoked, it has to obtain a intrinsic lock on all the static variables. I wrote a sample program, but it is not giving me the desired results.
    I have 3 threads, t1, t2, t3. t1 calls a static synchronized method crazy(), where i am using static int i. t2 and t3 calls a void function f2() and f3() which just prints i. Now i put a sleep in synchronized method crazy. I am expecting t1 to start and print i and go to sleep for 10 secs, release i and then t2 and t3 starts since crazy() holds an intrinsic lock on i. But the program calls t2 and t3 even if crazy puts the thread to sleep. What happend to the intrinsic lock on i ??
    class RunnableThread implements Runnable{
    static String i;
    void f2() {
    RunnableThread.i = "Two";
    System.out.println(RunnableThread.i);
    void f3() {
    this.i = "three";
    System.out.println(this.i);
    static synchronized void crazy() {
    try {
    i = "One";
    System.out.println(i);
    Thread.sleep(10000);
    System.out.println("Sleep done");
    catch (Exception e ) {
    e.printStackTrace();
    public void run() {
    System.out.println("Thread Name: " + Thread.currentThread().getName());
    if (Thread.currentThread().getName().equals("two"))
    f2();
    } else if (Thread.currentThread().getName().equals("three"))
    f3();
    else if (Thread.currentThread().getName().equals("one"))
    RunnableThread.crazy();
    public static void main(String args[]) {
    System.out.println("SOP from main");
    RunnableThread rt1 = new RunnableThread();
    RunnableThread rt2 = new RunnableThread();
    RunnableThread rt3 = new RunnableThread();
    Thread t1 = new Thread(rt1, "one");
    t1.start();
    Thread t2 = new Thread(rt2, "two");
    t2.start();
    Thread t3 = new Thread(rt3, "three");
    t3.start();

    lavanya.km wrote:
    I am trying to understand the "static synchronized threads"Never heard of it. You might want to clarify your terminology.
    - by theory when such a thread is invoked, it has to obtain a intrinsic lock on all the static variables. Nope. Doesn't happen.
    I wrote a sample program,Ah, I see. You're creating synchronized static methods. Those do not even come close to "obtaining an intrinsic lock on all the static variables," even if there were such a thing as an "intrinsic lock," which there isn't. A synchronized method is just shorthand for enclosing the entire body in a sync block. In the case of a non-static method, it syncs on the "this" object. In the case of a static method, it syncs on the Class object for the class where the method is declared.
    In no case does anything sync on "all the variables," static or not.

  • Synchronized method in a java class used by many interfaces

    My interface (idoc to file) is using a java class, which has one method that reads a table from a central database and after doing some calculations updates it.
    (The interface instantiate the class inside a user-defined function and calls the method there.)
    The problem is that if somebody sends 100 idocs at the same time, there can be a “dirty read”, I mean, a read just before other interface updates the table.
    We want the following:
    Interface 1:
    -          Read counter from the table (counter = 5 )
    -          Increment counter (counter = 6)
    -          Update table with that counter (table with counter = 6)
    Interface 2:
    -          Read counter from the table (counter = 6 )
    -          Increment counter (counter = 7)
    -          Update table with that counter (table with counter = 7)
    RESULT: The table has the counter = 7
    But what is happening is the following:
    -          Interface 1 reads (counter = 5)
    -          Interface 2 reads (counter = 5)
    -          Interface 1 increments counter (counter = 6)
    -          Interface 2 increments counter (counter = 6)
    -          Interface 1 updates table (table with counter = 6)
    -          Interface 2 updates table (table with counter = 6)
    RESULT: The table has the counter = 6 (WRONG)
    I made the method synchronized. What I was expecting was that only one interface (i1) could enter the method (read the table and update it) while other interfaces running at the same time would have to wait until i1 finished that method.
    My first test indicates that's not happening. Can anybody help me to find a solution?

    Hi Bhavesh,
    If the QOS is EOIO this means that the integration engine manage the call to the mapping program (and all the other blocks) inside an "internal" synchronized method.
    So this means that in this case you do not need to manage the queued access (synchronization) inside your custom java code because it is already enveloped in a queued block by XI.
    The problem that Jorge had can be easily reproduced using the sample code that follows:
    <b>class Synch Object</b>
    import java.util.Date;
    public class SynchObject {
         String strName;
         public SynchObject(String strName){
              this.strName = strName;
         public synchronized void syncWrite(String strCaller) throws InterruptedException{
              Date now;
              now = new Date();
              System.out.println("-- " + now.toLocaleString() + " " + strCaller + " entering syncWrite of " + strName);
              System.out.flush();
              Thread.sleep(1000);
              now = new Date();
              System.out.println("-- " + now.toLocaleString() + " syncWrite of " + strName + " called by " + strCaller );
              System.out.flush();
              Thread.sleep(1000);
              now = new Date();
              System.out.println("-- " + now.toLocaleString() + " " + strCaller + " leaving syncWrite of " + strName);
              System.out.println("");
              System.out.flush();
    <b>class Caller</b>
    public class Caller implements Runnable {
         String strName;
         SynchObject target;
         int intMax;
         public Caller(String strName, SynchObject target, int intMax) {
              this.strName = strName;
              this.target = target;
              this.intMax = intMax;
         public void run() {
              for(int i=0; i<intMax;i++)
                   try {
                        target.syncWrite(strName);
                   } catch (InterruptedException e) {
                        e.printStackTrace();
    <b>class Workbench</b>
    public class Workbench {
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              SynchObject sObj1 = new SynchObject("syncObj1");
              SynchObject sObj2 = new SynchObject("syncObj2");
              Caller c1 = new Caller("caller1",sObj1,2);
              Caller c2 = new Caller("caller2",sObj1,2); '[*CHANGE*]
              Thread ct1 = new Thread(c1);
              Thread ct2 = new Thread(c2);
              ct1.start();
              ct2.start();
    Run the workbench class to see what happen when setting QOS EOIO (the synch object is the same).
    To see instead what happen now (missing synchronization) you have to change in Workbench class the statement
    Caller c2 = new Caller("caller2",sObj1,2); '[*CHANGE*]
    with
    Caller c2 = new Caller("caller2",sObj2,2); '[*CHANGE*]
    The reason is that every instance of the mapping program declare a new instance of the "Synchronized object" so the calls are synchronized inside the same mapping program but not between several mapping program.
    Hope this give you a better idea on this problems with java synchronization, but if you have further doubts (I know it's a little bit tricky ) feel free to ask.
    Kind Regards,
    Sergio

  • 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();
    }

  • Dont understand what i should put down for host name for creating an email account?

    Dont understand incoming and outcoming server. dont know what to put for host name.
    can someone help?

    Do you have your email account set up on your computer e.g. on Outlook on a PC or Mail on a Mac ? If you have then you should be able to sync the settings from that to your iPad via the Info tab when connected to your computer's iTunes. Or you could just look at the settings for the account on your computer's email program and copy them over to the iPad manually.
    The incoming and outgoing server names are the servers that your email provider uses for your account to recieve (incoming) and send (outgoing) emails. A lot of accounts should be covered by the options that are listed on the 'Add Account' screen - for my Yahoo based accounts I just chose Yahoo! and the settings were set for me. If you have an account that isn't covered by those types then you could try logging into your account via a browser and see if they have any help for what settings you need to use. Different account providers have different settings, so if your can't find anything on your provider's site if you say on here who your provider is there might be somebody else here who has the same provider and can tell you what settings to use.

  • Dont understand what is wrong in code

    Task of my code that movieclip added on stage, change its size - height when change size of browsers(player) window thus height movieclip = height rowsers(player) window.
    That is my code:
    package
    import flash.display.*;
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.Event;
    public class ZhMenu extends Sprite
    public var menubg:MovieClip;
    public function ZhMenu()
    var menubg:  = new menuGrad();
    stage.scaleMode = StageScaleMode.NO_SCALE;
    stage.align = StageAlign.TOP_LEFT;
    stage.addEventListener(Event.RESIZE, onResize);
    this.addChild (menubg);
    menubg.x=0;
    menubg.width = 150;
    menubg.height = stage.stageHeight;
    public function onResize (event:Event):void
    var sh:Number = stage.stageHeight;
    menubg.x=0;
    menubg.width=150;
    menubg.height=sh;
    In the issue MovieClip menubg added on stage but when i change size of window i get error:
    TypeError: Error #1009: It is not possible to cause property or a method referring to object "null".
    at ZhMenu/onResize()
    And menubg dont change its size of course.
    I dont understand what is wrong.
    Plize help me if u know Action Script 3.0 better.

    Because you do not have an instance of the object... open a new fla and try these lines...
    // this will fail
    var menubg:MovieClip;
    menubg.x = 0;
    // this will not fail
    var menubg2:MovieClip = new MovieClip();
    menubg2.x = 0;

Maybe you are looking for

  • SmartView 11.1.2.2.000 - SmartView tab disappears from Excel 2010

    We are using SmartView 11.2.2.2.000 with Excel 2010.  The SmartView tab frequently disappears from the Excel menu, especially for one particular user.  Each time I walk him thru re-enabling it.  This user's files are usually multiple sheets.  Anyone

  • G530-4446 - Win7 - Scroll on touchpad no longer works

    Hey, I recently had to reinstall Windows 7 Ultimate on my G530-4446. My touchpad works, but the scrolling doesn't. When I go to Control Panel > Mouse - I notice that the settings are no longer there to control the scrolling. I remember there was a dr

  • Runner disappointed in lack of iPod+ compatability

    I've enjoyed my 5th gen. video iPod for well over a year; one of the main activities I use it for is running. Since I am getting more goal-oriented as a ruuner, I am disappointed to learn that this iPod model is not compatible with the Nike+iPod kit,

  • IE10 (jscript9.dll) crashes in my web application

    IE10 crashes when users work in my application. Reproduces in different workstations. (Web application written with GWT framework and in IE9 it works perfectly) Crash dump: Microsoft (R) Windows Debugger Version 6.12.0002.633 AMD64 Copyright (c) Micr

  • Help! Quiz - need to count score at the end

    I have a working quiz but I want to know how to get the score of the number of correct answers the person got but I can't seem to figure out the code for it. This is my code below. Can someone help me? stop();// movie clip waits on buttons gloss_mc._