Using String or Integer for synchronized blocks

Hi,
I have seen in the past the usage of structures like the following:
class MyClass {
  private static final String lockObject =  "XX";
  void mySyncFunction() {
    // do unsynchronized stuff
    synchronized( lockObject ) {
       // do synchronized stuff
    // do more unsynchronized stuff
}This code works, but I am unsure about using a String (or an Integer for that matter) instead of Object lockObject = new Object().
My guess is that if two different classes where to use the same String, for instance "XX" as above, that would mean trouble for the synchronized blocks. Is there any other argument I can use against this practice?

You can do this:
private static final String lockObject = new String("XX");You can guarantee more safety this way above. But anyway, not that it is bad, but is there any special reason for using a String or a Integer? Why not a simple Object for that synchronization?

Similar Messages

  • Synchronized {blocks} are not synchronized ?

    Hi
    I have a stored procedure containing a method with a synchronized block :
    public class MyClass {
    private static Connection conn;
    public static void insert(String stringData) {
    synchronized (conn) {
    //LOGGING
    Date startTime = new java.util.Date();
    ... some code ...
    //LOGGING
    Date stopTime = new java.util.Date();
    }I suppose that when a lot of concurrent users wil use the stored procedure, the synchronized block of code will not be executed at the same time. But when I do that my log dates are overcrossing, that means concurrent execution.
    How can I make this code really synchronized ??
    thanks,
    Xavier
    null

    radiatejava wrote:
    You mentioned there could be some thread caching - can you pls explain why/how ? Since the threads are not accessing the variable directly and instead they are querying the object using a method, why would the method return some old value ? I understand in case of direct access to the variable, a thread can cache the variable. Do you mean to say that threads will also cache the methods ? Otherwise, how is it possible to return the stale value. I am not expecting a blind answer like XClass is not thread safe (I too agree to this) but some explanation on how caching is being done with method calls too.You are thinking of it in a wrong way. It doesn't matter if methods are cached or not, methods are just static code blocks. The important thing to understand is that all data can be cached unless it is volatile or synchronized. The integer "inside" XClass is data, and that data might get cached, so e.g. getVar can return the cached value. It doesn't need to read the value from main memory. The same applies to setVar, it doesn't need to update the value in main memory.

  • Convert text box string into integer

    i have an html file in which i m using a text box , for entering amount i m using that text box entry at next jsp. i want to convert amount string into integer for further processing. At next jsp i m using:-
    String amount= request.getParameter("bal");
    int ammount1= Integer.parseInt(ammount);
    and in sql query i m using amount1 as:-
    ResultSet rs1 = st.executeQuery("update saving set balance = balance - amount1 where saving.account_no = '" + acc +"'");
    my problem is i m getting following error:-
    server encountered an internal error and
    exception:- numberformat exception
    please help me as soon as possible

    int ammount1= Integer.parseInt(ammount).toString();
    good to put try block too..
    try
    int ammount1 = Integer.parseInt(ammount).toString();
    catch(NumberFormatException e)
    ...}

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

  • Synchronized block

    Hi,
    Can any body comment on the following?
    "Only one of the synchronized methods in a class object can be executed by ANY thread at a time"
    Is the above true for synchronized blocks also, I mean if one thread is in a synchronized blk and executing wait, other thread cant be in the other synchronized blk executing notify???
    Zulfi.

    This means that wait notify must be encapsulated in a
    synchronize blk.Yes.
    Everything is fine but are there any other methods of
    an object where I can demonstrate that two threads
    cant call its two different methods at the same
    time??It will be nigh impossible to prove that two threads can't access a set of blocks of code at the same time, because even if they could, there's no way for you to force them to. If you don't see them in these blocks at the same time, it might be that they can be, but the scheduler just happened to work out such that they weren't.
    You could do something like this, which, though it doesn't prove anything, makes a pretty strong suggestion:
    public synchronized m1() {
        System.out.println("going to sleep");
        Thread.sleep(3600000); // sleep for an hour
        System.out.println("woke up");
    public synchronized m2() {
       System.out.println("In m2");
    }Have one thread call m1. Either have the invoking thread sleep for a few seconds or use wait/notify to make sure that the m1 thread actually gets cpu time and calls m1.
    Then start one or more threads that all m2. Since the first thread will be sleeping for an hour, and your program's not doing anything else, it's extremely extremely likely that the other thread(s) will get CPU time. If you don't see "In m2", it's almost a guarantee that the only reason is because they're waiting on the lock that the first thread holds.
    If you want to be more clever, have all the threads print out times just before and after they enter m1 and m2. Change the sleep time in m1, and observe the the time that the other threads wait tracks that.
    Note that this is still not a guarantee that those threads can't enter that block. But reading and understanding the docs, and seeing this behavior that is consistent with what the docs say, should be enough to convince you.

  • Is volatile necessary for variables only accessed inside synchronized block

    Hi,
    I am using ExecutorService to execute a set of threads. Then the calling thread needs to wait until all of them are done to reuse the thread pool to run another set of threads (so I can't use the ExecutorService.shutdown() to wait for all of the threads at this point). So I write a simple monitor as below to coordinate the threads.
    My question is: will it work? someone suggests that it might not work because it will busy spin on the non-volatile int which may or may not be updated with the current value from another thread depending on the whims of the JVM. But I believe that variables accessed inside synchronized blocks should always be current. Can anyone please help me to clarify this? Really appreciate it.
         * Simple synchronization class to allow a thread to wait until a set of threads are done.
         class ThreadCoordinator{
         private int totalActive = 0;
         public synchronized void increment(){
         totalActive++;
         notifyAll();
         public synchronized void decrement(){
         totalActive--;
         notifyAll();
         public synchronized void waitForAll(){
         while(totalActive != 0){
         try{
         wait();
         }catch (InterruptedException e){
         //ignore
         }

    Don't do that. Just save the Futures returned by the ExecutorService, and call get() on them all. This will only return when all the tasks have finished.

  • I am using a work laptop and have the same problem. When I try to change the "configure proxy", they only available option is "use this proxy server for all protocols". Could it be that my system administrator blocked me from changing it since they don'

    I am using a work laptop and have the same problem. When I try to change the "configure proxy", they only available option is "use this proxy server for all protocols". Could it be that my system administrator blocked me from changing it since they don't want us to use Firefox.
    == User Agent ==
    Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6.4; FNGP_SYS)

    Start Firefox in [[Safe Mode]] to check if one of your add-ons is causing your problem (switch to the DEFAULT theme: Tools > Add-ons > Themes).
    See [[Troubleshooting extensions and themes]] and [[Troubleshooting plugins]]
    If it does work in Safe-mode then disable all your extensions and then try to find which is causing it by enabling one at a time until the problem reappears.
    You can use "Disable all add-ons" on the ''Safe mode'' start window.
    You have to close and restart Firefox after each change via "File > Exit" (on Mac: "Firefox > Quit")

  • How to use At Selection Screen for fields whiledealing with Multiple Blocks

    Hi Guys,
                In my requirement i am having 4 blocks.1st block with raduio buttons for activating the opther 3 Blocks.
                  In these 3 blocks i am having some fields.
           How to do Validation for these fields.?
    I am using At Selection-screen on S-SCAD1. I am getting error"S_SCACD1 is neither a selection screen nor a Parameter"
    On the top of this" At Selection-screen on S-SCAD1" I am having"AT SELECTION-SCREEN OUTPUT."
                    Can anybody tell me how to solve this error?
    Thanks,
    Gopi.

    If you are using your block name than you should use like:
    AT SELECTION-SCREEN ON BLOCK S-SCAD1.
    Regards,
    Naimesh Patel

  • I need a formula to convert a date into an integer (for use in Lookout)

    I have a DATA logger with the following:
    40001 = 4 (2004)
    40002 = 2 (February)
    40003 = 5 (5th)
    40004 = 13 (1:00pm)
    40005 = 12 (12 minutes)
    Lookout requires a date that it understands (eg. January 1, 1900).
    All I need is a basic formula to convert the date and time.
    This formula does not need to be specifically written for Lookout. Just a basic formula that I can do on paper or a calculator.
    I can integrate that formula into the Lookout software myself.

    Hello Smigman,
    First of all, I apologize in advance for not giving you "just the formula." And for the lengthy explanation (had to wait till after work hours), which you are very likely aware of already. I am writing this response in much detail so that it may benefit others.. hopefully And so that we understand the underlying principle involved, which will hopefully help us in building the formula the best way that suits us.
    As you have figured out, the data and time in Lookout is represented as a real number. This real number's integer portion represents days, and the decimal portion denotes time. The integer portion is basically the number of days since 01/01/1900. And the decimal portion is the number of seconds since midnight.
    So, for instance, if you insert the today() Expression in Lookout, you'll get a integer 38022 (which corresponds to today, Feb. 5th, 2004). In other words, today is the 38022nd day since 01/01/1900. Tomorrow, Feb. 6th 2004, will be 38023 and so on.
    The decimal part denotes time. A day has 24*60*60 = 86400 seconds, obviously. So, 1/86400 = 1.15741E-5 roughly represents one second. For instance, 38022.00001157 will give 02/05/2004 00:00:01.
    Coming to the formula now, for Time, first convert it to total seconds from midnight. E.g., 5:15:07pm would be (17*60*60) + (15*60) + 7 = 62107 seconds total since midnight. To get the Lookout's decimal part, divide this by 86400.
    62107/86400 = 0.71883102
    Therefore, 38022.71883102 would now give 02/05/2004 17:15:07. Computing Time is relatively easy.
    For the Date -- which is more complicated-- you could keep track of the total number of days either from 01/01/1900, or better still, a more recent day, like say 12/31/2003, which corresponds to 37986. To this reference you will keep adding 1 for each additional day to get the number for the current day. Note, you will have to accomodate leap years (Feb. 29th of this year, for instance).
    It's very helpful to have the reference day as the last day of the past year. That can be derived by counting the number of days since 01/01/1900 as follows:
    104 years * 365 days = 37960;
    + 1 day for each leap year
    A leap year is a year divisible by 4 (and 400 if the year ends with two zeros). There were 26 leap years from 1900 till 2003.
    So, 37960 + 26 = 37986. 12/31/2003 is thus represented by 37986.
    To get the integer for the Current Date we would first find what day of the year it is. Then add it to the reference day. Feb 5th, is the 36th day of the year. Adding this to 37986, gets us 38022.
    In your case you will have to come up with the correct day of the year using registers 40002 and 40003. Not sure if this helped or confused you more.
    I tried
    Khalid

  • How to search for upper/lower case using string using JAVA!!!?

    -I am trying to write a program that will examine each letter in the string and count how many time the upper-case letter 'E' appears, and how many times the lower-case letter 'e' appears.
    -I also have to use a JOptionPane.showMessageDialog() to tell the user how many upper and lower case e's were in the string.
    -This will be repeated until the user types the word "Stop". 
    please help if you can
    what i have so far:
    [code]
    public class Project0 {
    public static void main(String[] args) {
      String[] uppercase = {'E'};
      String[] lowercase = {'e'};
      String isOrIsNot, inputWord;
      while (true) {
       // This line asks the user for input by popping out a single window
       // with text input
       inputWord = JOptionPane.showInputDialog(null, "Please enter a sentence");
       if ( inputWord.equals("stop") )
        System.exit(0);
       // if the inputWord is contained within uppercase or
       // lowercase return true
       if (wordIsThere(inputWord, lowercase))
        isOrIsNot = "Number of lower case e's: ";
       if (wordIsThere(inputword, uppercase))
         isOrIsNot = "number of upper case e's: ";
       // Output to a JOptionPane window whether the word is on the list or not
       JOptionPane.showMessageDialog(null, "The word " + inputWord + " " + isOrIsNot + " on the list.");
    } //main
    public static boolean wordIsThere(String findMe, String[] theList) {
      for (int i=0; i<theList.length; ++i) {
       if (findMe.equals(theList[i])) return true;
      return false;
    } // wordIsThere
    } // class Lab4Program1
    [/code]

    So what is your question? Do you get any errors? If so, post them. What doesn't work?
    And crossposted: how to search for upper/lower case using string using JAVA!!!?

  • Using variable in connection string returns 0 for variable.

    hi all- I am pulling data from a visual forxpro database and the connection string is as follows: 
    Data Source=\\ServerName\FolderName\AR;User ID=Domain\svcAct;Provider=VFPOLEDB.1;Persist Security Info=True;
    I created a variable called CurrentARPath and stored the path
    \\ServerName\FolderName\AR
    I then tried using this variable in the Expression property of the connection string as follows:
    "Data Source="+(DT_WSTR, 20)@[User::CurrentARPath] + ";User ID=Domain\\svcAct;Provider=VFPOLEDB.1;Persist Security Info=True;"
    However, the above expression is evaluating the variable to 0 as shown below; this is causing the connection in connection manager to go down(offline) and the OLED data source is complaining.
    Data Source=0;User ID=Domain\svcAct;Provider=VFPOLEDB.1;Persist Security Info=True;
    any idea what i am doing wrong here? thanks in advance!

    What datatype is CurrentARPath? Are there any
    configurations on the connection string or variable?
    Which
    package protection level are you using?
    CurrentARPath data type - Char
    there are no configurations on the connection string. one thing that i should mention is that i have created a variable  called ArPath of type object and using it in the for each loop container. this variable gets populated using an execute SQL statement.
    i am then mapping the vale from ArPath to CurrentARPath in the loop container.
    Package protection level is default(encrypt sensitive)
    thanks for the help.

  • Can i use standard workflow for invoice block ? (BUS2081 . WS20000397)

    Hi Experts ,
    Please any one help me to use the standard workflow for Handlinig invoices blocked(T-code MIRO ). 
    I want an email sent , when  PO invoice is posted and blocked with attched PDF format .
    checked Business object BUS2081 . and Workflow WS20000937.
    But not sure how to use . Please help me to used to get the mail using the standard Workflow .
    Thanks .

    HI
    Iam not pretty much sure about MM or Invoices I found one of the [SAP Help documentation|http://help.sap.com/erp2005_ehp_04/helpdata/EN/0e/0e3b0cb84111d3b5b2006094192bbb/frameset.htm] . This might help you to process ahead.
    Regards
    Pavan

  • Do third party replacement tips fit on the apple in ear headphones? I prefer foam tips as they block out much more sound, but I'm not sure if Apple use the standard fitting for headphone tips!?!?!?!

    Do third party replacement tips fit on the apple in ear headphones? I prefer foam tips as they block out much more sound, but I'm not sure if Apple use the standard fitting for headphone tips!?!?!?!

    Answer found. Please find below an amazon review explicitly mentioning adding third party foam tips. Sounds like they fit and work like a dream:
    "As a audio engineer, I own about a dozen different sets of earphones and in-ear 'phones. My favorite, by far, are my sure SE530s. I have some Sennheiser cx400s which are good workhorses, but lack the finesse, clarity and stunning accuracy of the Shures. For convenience, I bought the Apple's, as I wanted something I could use with the phone for calls.
    I found the sound to be quite clear and beautifully clean, but like many, no matter how I tried, the stock Apple tips never made a good seal. The seal is absolutely essential to getting bass out of a balanced armature design. For you non-engineers, just trust me that if you don't have a proper seal, you will have no bass.
    In my case, I think the trouble had to do with the largest size being a tiny bit too small, and the silicon being too rigid, yet slick, so they left small airgaps and were easy to remove. I tried using some foam tips from a third party, but their large was more of a medium, and never came close to a snug fit.
    As an experiment, I dug around in my ear-tips from my Shure's and tried their rubber tips which are about the same size as Apple's large tips, but made of a more pliant and slightly sticky rubber.
    OMG, what a transformation. Suddenly the sound blossomed, the bass became rich and well balanced, and the "top-heavy" sound was totally mellowed into a rich, well balanced and incredibly detailed presentation.
    Make no mistake, these are the best 'phones under $200 I have ever heard. The bass is deep and warm, very detailed, and totally lacking fuzz or buzz that I can hear in the Sennheiser set. Look at getting tips from a better headphone. The trick is it has to have a soft rubber base that can expand over Apple's slightly larger stub. Some tips, like the Shure foam tips, have a rigid plastic sleave in the tip to keep it's position correct, and these won't expand over the larger Apple posts."

  • I need to use Adobe Flash PLayer for an online conference.  I get a pop-up blocked message.

    I need to use Adobe Flash PLayer for an online conference.  I get a pop-up blocked message. I have already unblocked pop-ups as far as I can see.
    Maybe I'm missing something?

    After installing Flash, reboot your Mac and relaunch Safari, then in Safari Preferences/Security enable ‘Allow Plugins’. If you are running 10.6.8 or later:
    When you have installed the latest version of Flash, relaunch Safari and test.
    If you're getting a "blocked plug-in" error, then in System Preferences… ▹ Flash Player ▹ Advanced
    click Check Now. Quit and relaunch your browser.

  • I already have flashplayer on my mac. I have been using online video tutorials for learning, but suddenly all my YouTube vodeos say "plug-in blocked". I follow the instructions for installing or updating, but nothing has helped. I have looked everywhere i

    I already have flashplayer on my mac. I have been using online video tutorials for learning, but suddenly all my YouTube vodeos say "plug-in blocked". I follow the instructions for installing or updating, but nothing has helped. I have looked everywhere in Safari help with no success. How can I restore this plug-in, PLEASE?
    Austin Moore
    Knoxville, Tennessee

    I already have flashplayer on my mac. I have been using online video tutorials for learning, but suddenly all my YouTube vodeos say "plug-in blocked". I follow the instructions for installing or updating, but nothing has helped. I have looked everywhere in Safari help with no success. How can I restore this plug-in, PLEASE?
    Austin Moore
    Knoxville, Tennessee

Maybe you are looking for

  • Report for displaying the order number & order date..

    HI ALL, can any body help me for displaying the order number,customer name,material name & order date..in report i dnt know the which are the table i need to use... can anybody tell me which are table do i need to use and fields in tables input to re

  • Oracle 12c installation in local windows 32 bit

    Hi, I tried to install oracle 12c in my laptop. but installation is finised successfully. i could not create a database yet. can any one please help ?

  • Query key Date Variable not working

    Hi Folks -      I am coming across an issue with which some of you might be able to help me. I have a time dependent master data object which I've marked as a datatarget and have created a report on it. I wanted to give the user an option of specifyi

  • How to make as selection variable

    Hi All we have one variable plant. the variable is properties are: genral properties: Type of variable : Characteristic Processing by : Authorization Reference charateristic : plant. Details: Variable represents : Multiple single values variable is :

  • How do I get Siri to work on my 4S

    I picked up my 4s last night after a ridiculously long wait at UPS. I can't help but wonder if Siri isn't supposed to do something other than say "Sorry, X, something is wrong. Please try again."