Synchronization on a static object

If I have a code like:
synchronized(_otherParsers)
_otherParsers = new Vector();
} knowing the _otherParsers is a static object in the class, the synchronization will block all access to the object or it will block the access to the sync. block?
OBS: So when one thread enters the synchronized block, accesses to that object by other threads are blocked until the original thread exits the synchronized block. [PENDING: verify previous statement, and figure out if synch'ed blocks block out all method calls on the object or just synch'ed ones] (quote from Java Tutorial, http://java.sun.com/docs/books/tutorial/together/bingo/synchronized.html)

IIRC, when using synchronize(someObject) then
someObject is locked, meaning that the original object
isn't locked. So other methods will execute correctly.let's say the following:import java.util.Vector;
public class A {
  public static Vector v = null;
  public A() {
    v = new Vector();
  public static void main(String[] args)
     B b = new B();
     new Thread(b).start();
     new A();
class B implements Runnable {
  public void run() {
    synchronized(A.v) {
        A.v = new Vector();
        A.v.add("test");
}As you can clearly see, the static vector, member of A class is initialized twice (once by the new A() in the main method of A class and once by A.v = new Vector() in the run() method of B class). Assuming the thread enters the synchronized block before the call to new A() in the main method, when that call ocures, is the A.v object locked? or not?

Similar Messages

  • Using public static object for locking thread shared resources

    Lets Consider the example,
    I have two classes
    1.  Main_Reader -- Read from file
    public  class Main_Reader
         public static object tloc=new object();
           public void Readfile(object mydocpath1)
               lock (tloc)
                   string mydocpath = (string)mydocpath1;
                   StringBuilder sb = new StringBuilder();
                   using (StreamReader sr = new StreamReader(mydocpath))
                       String line;
                       // Read and display lines from the file until the end of 
                       // the file is reached.
                       while ((line = sr.ReadLine()) != null)
                           sb.AppendLine(line);
                   string allines = sb.ToString();
    2. MainWriter -- Write the file
    public  class MainWriter
          public void Writefile(object mydocpath1)
              lock (Main_Reader.tloc)
                  string mydocpath = (string)mydocpath1;
                  // Compose a string that consists of three lines.
                  string lines = "First line.\r\nSecond line.\r\nThird line.";
                  // Write the string to a file.
                  System.IO.StreamWriter file = new System.IO.StreamWriter(mydocpath);
                  file.WriteLine(lines);
                  file.Close();
                  Thread.Sleep(10000);
    In main have instatiated two function with two threads.
     public string mydocpath = "E:\\testlist.txt";  //Here mydocpath is shared resorces
             MainWriter mwr=new MainWriter();
             Writefile wrt=new Writefile();
               private void button1_Click(object sender, EventArgs e)
                Thread t2 = new Thread(new ParameterizedThreadStart(wrt.Writefile));
                t2.Start(mydocpath);
                Thread t1 = new Thread(new ParameterizedThreadStart(mrw.Readfile));
                t1.Start(mydocpath);
                MessageBox.Show("Read kick off----------");
    For making this shared resource thread safe, i am using  a public static field,
      public static object tloc=new object();   in class Main_Reader
    My Question is ,is it a good approach.
    Because i read in one of msdn forums, "avoid locking on a public type"
    Is any other approach for making this thread safe.

    Hi ,
    Since they are easily accessed by all threads, thus you need to apply any kind of synchronization (via locks, signals, mutex, etc).
    Mutex:https://msdn.microsoft.com/en-us/library/system.threading.mutex(v=vs.110).aspx
    Thread signaling basics:http://stackoverflow.com/questions/2696052/thread-signaling-basics
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Cluster and static object.

    I have application worked in cluster. Is some possibility to propagate change in static object to all application in cluster.

    You can use application context (javax.naming.InitialContext) and bind (set), rebind (set new value), lookup (get) and unbind (remove) variables (must be serializable).
    You must corect configure RMI replication.
    Changes ist propagated acros all nodes in cluster. (but unbind don't work correct - it work only locale (bug?))

  • Client-Side Caching of Static Objects

    Hi,
    We just installed SPS12 for NWs.  I learned of this new client-side caching of static objects while reading through the release notes, and I went in to our portal to check it out.  I went to the location where the <a href="http://help.sap.com/saphelp_nw04s/helpdata/en/45/7c6336b6e5694ee10000000a155369/content.htm">release notes</a> (and an <a href="https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/6622">article in the blog</a>) specified, System Administration > System Configuration > Knowledge Management > Content Management > Global Services.
    Problem is that I do not see Client Cache Service and Client Cache Patterns.  I enabled "Show Advanced Options," but I do not see those two configuration items.
    Does anyone know why I am not seeing those two configuration items and how I can get to those?
    Thank you.

    Hi,
    We are using SPS 12.
    KMC-CM  7.00 SP12 (1000.7.00.12.0.20070509052145) 
    KMC-BC  7.00 SP12 (1000.7.00.12.0.20070509052008) 
    CAF-KM  7.00 SP12 (1000.7.00.12.0.20070510091043) 
    KMC-COLL  7.00 SP12 (1000.7.00.12.0.20070509052223) 
    KM-KW_JIKS  7.00 SP12 (1000.7.00.12.0.20070507080500)

  • Layer static objects/text on top of interactive elements

    is it possible to layer static objects/text on top of interactive elements (including scrollable slideshows or MSO) in INDD CC for DPS/Content Viewer?  The static objects (on their own layer) disappear when viewed on tablet in Content Viewer

    Thank you so much!
    Taylor Guilmette | Senior Graphic Designer
    CBRE/Grossman Retail Advisors
    33 Arch Street, 28th Floor | Boston, MA 02110
    T +1 617 912 7052 | F +1 617 912 6867
    [email protected]<mailto:[email protected]> | www.cbre.com/taylor.guilmette<http://www.cbre.com/taylor.guilmette>
    Follow CBRE/Grossman Retail Advisors: @CBREGRA<https://twitter.com/CBREGRA>

  • Third-party C++ Driver : Static object

    Hello,
    I'm writting a C++ driver for Labview RT.
    I'm using Visual C++ to compile and link this driver.
    I have some initialisation problem on the target.
    It seems that static object are not created correctly. All members are not created correctly and it crashes as soon as I use these objects.
    Could someone confirm this problem ?
    Is there someone develop a C++ driver (based on VISA) for Labview RT ? Thanks for your responses !
    David Chuet

    David:
    For starters, note that NI does not officially support MSVC-built DLLs on LabVIEW RT. I believe we only officially support DLLs built with LabVIEW or CVI. However, in most cases MSVC-built DLLs will work fine.
    As to your specific question, you are correct. C++ static objects don't get initialized. Realize that the LabVIEW RT OS (Phar Lap ETS) is Win32-like. In other words, it is not 100% compatible with Win32 and MSVC, but it is extremely compatible with a large subset of the two. This is probably the biggest difference I can think of.
    My suggestion is to have static pointers to objects, then initialize them in your DLLmain. That does work and that's how we do it in NI-VISA.
    Dan Mondrik
    National Instruments

  • Static Objects.

    If an object were static, would its non-static members act like static? What kind of problems would happen if two threads try to use this object to call one of its non-static functions? Would any member of this object (either static or non-static) be part of a critical section?

    jverd wrote:
    wpafbuser1 wrote:
    There's no such thing as a static object (since there's no instance).No, there's no such thing as a static object because the property of being static or not is not applicable to objects. Saying there's no instance is wrong, since, if there's an object, there's obviously an instance--the object.I wrote too fast, I meant there's no instantiation. Obviously there's an object/instance. But my thinking was flawed there anyway. :)
    A class is considered static when it's fields and methods are static.No. A class is static when it's a nested class and it's declared static. A class is often incorrectly called static simply by virtue of it having only static members. Regardless of whether the class is static, all instances of that class are neither satic nor non-static.The term static, incorrectly used or not, I was referring too top-level classes not inner classes.
    I guess what I'm saying is that if you include non-static methods or fields in your class, it's no longer a static class Wrong.
    class Outer {
    static class Nested {
    int x;
    void foo() {}
    }Nested has a non-static member variable and a non-static method, but it's still a static class, because it's declared static.Again, we're talking about 2 different things now.

  • How to persistent static object

    JDO always assigns a StateManager to a PersistenceCapable object when
    creating instance. If an object is static, it'll keep its StateManager for
    ever after instantiation. So If I excute the following code repeadly, kodo
    will complain that persistence manager has been closed.
    1) Get PersistenceManager
    2) Begin transaction
    3) Get object from datastore. If not exist, create a new object. This
    object is a static.
    4) Commit transaction
    5) pm.close
    For the first time, kodo will assign a new StateManager to this static
    object. But for the second time, exception, "persistence manager has been
    closed", will arise when excuting some of object's methods. Because each
    StateManager object owns a PersistenceManager object. If this pm is
    closed, according StateManager object is also useless.
    After enhancing, kodo will change some getter/setter methods to
    according jdo getter/setter ones. These methods may invoke
    startManager.isLoaded(), which invokes pm.isActive(). Unfortunately, pm
    has been closed.
    Any other tricky methods to persistent static object ?
    Thanks !

    Dear Marc,
    Thanks for your kind help. It's an effective advice to prevent
    persistent object from being static.
    However, what if the object to be persistent is an enumeration type
    constant ? For example :
    public class MyEnumType
    private String name = null;
    private int value = 0;
    protected MyEnumType( String name, int value )
    this.name = name;
    this.value = value;
    public static final TYPE_1 = new MyEnumType( "type 1", 1 );
    public class EnumTypeUseClass
    private MyEnumType type = null;
    public void setType(..) {..}
    public MyEnumType getType() {..}
    public class TestClass
    public void f()
    PersistenceManager pm = null;
    try
    // Obtain pm
    pm = ...;
    pm.currentTransaction().begin();
    EnumTypeUseClass use = new EnumTypeUseClass();
    // Obtain myenumtype object from datastore
    MyEnumType type = getJdoObject( pm, MyEnumType.class, "value ==" +
    MyEnumType.TYPE_1.getValue() );
    // Following line will cause "PersistenceManager has been closed"
    exception
    use.setType( type );
    pm.makePersistent( use );
    pm.currentTransaction().commit();
    catch( .. )
    finally
    pm.close();
    public static void main( String args[] )
    for( int i = 0; i < 10; i ++ )
    f();
    Actually, exception is caused by MyEnumType.TYPE_1.getValue() because
    this object's pm has been closed in the first loop time.
    Now I solved this problem by not persistent MyEnumType objects, and
    change type field in EnumTypeUseClass from MyEnumType to int.
    But I still wonder how to persistent static objects.
    Maybe your first advice is feasible, but I think it will make your
    program tangly. Do you think so ? :)
    Marc Prud'hommeaux wrote:
    Liang-
    You are correct that a persistent instance must be associated with a
    PersistenceManager. You could always just leave the PersistenceManager
    open (if using optimistic transaction, Kodo won't tie up database
    resources in this case). Another option is to not have the singleston
    instance be a static variable, but have it be obtained via a factory
    method that takes a PersistenceManager argument.
    If this doesn't help, perhaps you could help clarify the situation by
    posting some code that shows that you would like to do?
    In article <[email protected]>, Liang Zhilong wrote:
    JDO always assigns a StateManager to a PersistenceCapable object when
    creating instance. If an object is static, it'll keep its StateManager for
    ever after instantiation. So If I excute the following code repeadly, kodo
    will complain that persistence manager has been closed.
    1) Get PersistenceManager
    2) Begin transaction
    3) Get object from datastore. If not exist, create a new object. This
    object is a static.
    4) Commit transaction
    5) pm.close
    For the first time, kodo will assign a new StateManager to this static
    object. But for the second time, exception, "persistence manager has been
    closed", will arise when excuting some of object's methods. Because each
    StateManager object owns a PersistenceManager object. If this pm is
    closed, according StateManager object is also useless.
    After enhancing, kodo will change some getter/setter methods to
    according jdo getter/setter ones. These methods may invoke
    startManager.isLoaded(), which invokes pm.isActive(). Unfortunately, pm
    has been closed.
    Any other tricky methods to persistent static object ?
    Thanks !
    Marc Prud'hommeaux [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • Trouble understanding static objects

    Hello,
    I have trouble understanding static objects.
    1)
    class TestA
    public static HashMap h = new HashMap();
    So if I add to TestA.h from within a Servlet, this is not a good idea, right?
    But if I just read from it, that is ok, right?
    2)
    class TestB
    public static SimpleDateFormat df = new SimpleDateFormat();
    What about TestB.df from within a Servlet? Is this ok?
    example: TestB.df.format(new Date(1980, 1, 20));

    There is exactly one instance of a static member for every instance of a class. It is okay to use static members in a servlet if they are final, or will not change. If they may change, it is a bad idea. Every call to a servlet launches a new thread. When there are multiple calls, there are multiple threads. If each of these threads are trying to make changes to the static memeber, or use the static memeber while changes are being made, the servelt could give incorrect results.
    I hope that helped..
    Thanks
    Cardwell

  • Static Object Vs. Lots of referece passing...

    I am implementing a discrete event simulator for which there is only ever one "executor" object and one "output manager" object used to advance time and deal with output to files. However many objects in the simulator need access to these objects and there "security" is not an issue. I was wondering if anyone knows if it is gives better performance to make these classes with static methods or whether I should pass a reference to them to nearly every other object. Also do you know why whatever one is beter?
    Cheers,
    Mark

    For this project performance really is the issue
    though. My concern is that if I pass a reference of
    an object to lots of other objects (in the order of
    100,000) that is simply a waste of time and memory
    So let's get this straight. You can have 100,000 Objects, but you can't add one reference varialble to each.
    if making the objects access methods static may
    remove this I will happily accept this over
    management and testability issues. What do you think making the method static will save you, exactly?
    What I really want to know is for example...
    is the above less effective than...No, generally , static methods are less effective than instance methods.
    if StaticObjectType in the later example is the same
    as the OtherObjectType in the first example., but
    with a static method, given that only one instance of
    OtherObjectType will ever exist. This makes no sense. There is no such thing as a 'static' Object. Static only applies to references and methods and nested classes.
    My worry is that passing this object address around
    and storing it as a field will be far less effective
    than having just a static method, although I am not
    sure this is true.There is a slight performance hit when calling an instance method over a static method. Declaring a method final may remove this. When I say slight, I mean really slight. Both methods are called in the basically the same manner.
    As this is happening thousands of times a second in
    this program and storage and speed are key really
    just need to choose the most efficient
    implementation.Again I don't understand how you can afford o have thousands of Objects but can't afford an extra reference on them.

  • Static Object doesn't get collected

    Hi,
    I have a class JLog to log all the messages to a file. The JLog class is in a jx.war file which is deployed to the application server JBoss.
    If the jx.war is deployed once, the messages printed to the file only show up once, which is fine.
    But if the jx.war is deployed twice, the messages printed to the file show up twice.
    If the jx.war is deployed three times, the messages show up three time and so forth.
    My question is why the static object jLogger from the previous deployments doesn't get collected.
    I think switching to Singleton implementation will solve this issue.
    But are there any other ways to sovle it?
    public class JLog {
         private static int logLevel = getLogLevel();
         private static long line = 0;     
         static Logger jLogger;
         private static PatternLayout jLayout = null;
         private static Appender jAppender = null;
         public static void toLogger(String msg ) {                    
              try {
                   if ( jLogger == null ) {
                        // System.out.println(" *** get a new logger *** ");
                        jLogger = Logger.getLogger(JLog.class.getName() );                    
                        jLogger.setAdditivity( false );
                        jLogger.setLevel( Level.ALL );
                   if ( jLayout == null ) {
                        // System.out.println(" * new patternLayout " );
                        String pattern = "%d{yyyy-MM-dd HH:mm:ss,SSS} - %m%n";                    
                        jLayout = new PatternLayout( pattern );
                        pattern = null;
                   if ( jAppender == null ) {
                        // System.out.println(" * new FileAppender " );
                        String filename = "jx.log";
                        String dataPattern = "'.'yyyy-MM-dd";
                        jAppender = new DailyRollingFileAppender( jLayout, filename, dataPattern );                    
                        filename = null;
                   jLogger.addAppender( jAppender );               
                   jLogger.debug( msg );               
              } catch (Exception e) {
                   System.out.println("Exception! JLog.toLogger >>> " + e.getMessage() );
                   e.printStackTrace();
              } // try
         } // toLogger
    }

    Each application in an application server is independant.
    This means singletons, and static values appear once per application. i.e. each application has its own copy.

  • Static object vs non-static object......

    What is the purpose of static object????
    is there any example showing that the advantage of declaring a static object rather than a non-static object??
    secondly, why static object/primitive data is initialized before non-static object/primitive data?
    apreciate for any respond

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Random;
    public class Test3 extends JFrame {
      JDesktopPane jdp = new JDesktopPane();
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        content.add(jdp, BorderLayout.CENTER);
        JButton jb = new JButton("New Thingy");
        content.add(jb, BorderLayout.SOUTH);
        jb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            try { jdp.add(new Thingy(jdp.getWidth(), jdp.getHeight())); }
            catch (Exception e) { System.out.println(e.getMessage()); }
        setSize(300, 300);
        setVisible(true);
      public static void main(String[] args) { new Test3(); }
    class Thingy extends JInternalFrame {
      Random r = new Random();
      static int count=0; //  HERE IT IS!!!
      public Thingy(int w, int h) throws Exception {
        if (count==6) throw new Exception("Too Many Thingies");
        setTitle("T-"+(++count));
        setBounds(r.nextInt(w-100),r.nextInt(h-50),100,50);
        setVisible(true);
    }

  • Accessing static object across portlets

    hi
    in portal server 7.1, i had a static object that is used by all the portlets by usebean tag in jsp. it works fine
    for all the tabs that i created. But when i tried to access the page in new browser, the same static object exists.
    how, the object exists for the new session also. the bean code i called from jsp is...
    public class ObjectDispatcher {
    /** Creates a new instance of ObjectDispatcher */
    private static SessionDispatcher dispatcher;
    public ObjectDispatcher() {  }
    public SessionDispatcher getDispatcher() {
    if (dispatcher == null) {
    dispatcher = new SessionDispatcher();
    return dispatcher;
    the jsp portlet code to call the bean is :
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8" import="com.test.SessionDispatcher"%>
    <%@ page import="javax.portlet.*"%>
    <%@ taglib uri="http://java.sun.com/portlet" prefix="portlet"%>
    <portlet:defineObjects />
    <%PortletPreferences prefs = renderRequest.getPreferences();%>
    <jsp:useBean id="objdispatcher" class="com.test.ObjectDispatcher" scope="session"/>
    <%
    SessionDispatcher bosession = objdispatcher.getDispatcher();
    out.println(" got dispatcher "+bosession);
    String sessid = bosession.getSessionID();
    %>
    the bosession object is printed for all the portlets across the tab give the same portlet object that is fine.
    but for new browser also, the same object is printing.
    i want to create new object when new explorer opens.
    please help to resolve this issue

    hi
    in portal server 7.1, i had a static object that is used by all the portlets by usebean tag in jsp. it works fine
    for all the tabs that i created. But when i tried to access the page in new browser, the same static object exists.
    how, the object exists for the new session also. the bean code i called from jsp is...
    public class ObjectDispatcher {
    /** Creates a new instance of ObjectDispatcher */
    private static SessionDispatcher dispatcher;
    public ObjectDispatcher() {  }
    public SessionDispatcher getDispatcher() {
    if (dispatcher == null) {
    dispatcher = new SessionDispatcher();
    return dispatcher;
    the jsp portlet code to call the bean is :
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8" import="com.test.SessionDispatcher"%>
    <%@ page import="javax.portlet.*"%>
    <%@ taglib uri="http://java.sun.com/portlet" prefix="portlet"%>
    <portlet:defineObjects />
    <%PortletPreferences prefs = renderRequest.getPreferences();%>
    <jsp:useBean id="objdispatcher" class="com.test.ObjectDispatcher" scope="session"/>
    <%
    SessionDispatcher bosession = objdispatcher.getDispatcher();
    out.println(" got dispatcher "+bosession);
    String sessid = bosession.getSessionID();
    %>
    the bosession object is printed for all the portlets across the tab give the same portlet object that is fine.
    but for new browser also, the same object is printing.
    i want to create new object when new explorer opens.
    please help to resolve this issue

  • Resetting a static object?

    Okay I've created an application to create and monitor a number of other applications. My contorller application consists of a main method and a number of static methods and objects. I'm trying to create tests to test the functionality of the application.
    The problem I have is it's static. once I run the main method once variables get set, timers started, sockets locked ect. This makes it very difficult to run independent tests as every test after the first already has the application running and changes made to it's static variables. What I would like is at the end of each test the static object acted as if the application was closed: releasing locks it held, resetting variables to default, and calling the onExit method. That way the next test in the suit won't be effected by changes made to static variables in the previous state.
    Does anyone know an easy way of doing that? For now I'm calling the my onExit method directly which stops timers and releases sockets, but I still don't feel confident that my tests are running truely independently so long as they are sharing a static object.

    Thank you for the quick responce. I'll try what you suggested
    And your right there are a few methods that don't have to be static, the design decision was made before I joined the project and it was just easier to go along with it then get them to rewrite documentation. Still most of the work is being done in the Main method (or timers declared there). That would have to stay static even if I wanted to change it wouldn't it?
    Teddy the problem is the applications is pretty huge and has many variables, I'm too lazy to reset them all by hand. Plus there are things done in clean up of an application besides resetting variables, For instance Java Logger won't add the </log> tag at the end of a log because the application hasn't ended while my test Suit is still running. Sure I could get around that, but I was curious if there was a way to do what I was thinking, so I asked. Best way to learn a language is to try doing something differnt every now and then

  • Handling static objects

    Hi,
    I would like to know how are static objects handled in java
    Questions:
    1) What is the lifetime of a static object.
    2) can a static object called through any class on the jvm be reclaimed
    to phrase the above question better, If a class has a static object can i free the memory at anytime.
    3) Can i have links to handling of objects by the jvm if any.
    Any pointers are highly appreciated.
    Thanks and regards,
    myraid_77

    Static variables are associated with a class, not an instance.
    So, as long as the class is loaded, the static variable will remain.
    You would have to create your own classloader, and load a class ( containing the static variable ), through the classloader..... then later on null all references to the classloader, to unload the class from memory.
    The easiest way to reclaim memory from a static variable is to set it to null.
    regards,
    Owen

Maybe you are looking for

  • Export in AddressBook are from the old Tiger DB

    Hi, When I export my address book from AddressBook on Leopard, it exports only my old address book from Tiger... In my Application Support/AddressBook I have this 2 files of DB : -rw------- 1 dulrich dulrich 421888 Oct 30 08:10 AddressBook-v22.abcddb

  • LOV filter issue

    When we enter a value on the base page and click on the LOV we get the usual popup window. When we now try to conduct a search within the popup window the results are filtered so we can onlly return the intial value. In other words the second query w

  • Error 1906, 1603,1628

    I tried to update my iTunes software and I received the error message 1906: C://Windows\Installer\ae8c8c.msi Error - 2147286775. I tried to reupdate the software after turning off my antivirus software and I received Error 1603. So I restarted my com

  • Reflection class

    I have a problem. We can use reflector class to get the class name, method names and class variables. But is it possible to get method variables using the same logic? Please help. Thanks in advance.

  • Finder restarting

    This afternoon Software Update informed me there was an update to iTunes and Quicktime available. Since installing the updates and restarting, the finder doesn't run for more than about a minute at a time. The finder crashes and restarts about every