Shared Objects for Threads

Hi,
Currently studying for SCJP exam and wondering is there a different between the following codes
public class Test extends Thread
static Object obj = new Object();
static int x, y;
public void run()
   synchronized(obj)
     for(;;)
      x++; y++; System.out.println(x+" "+y);
public static void main(String[] args)
   new Test().start();
   new Test().start();
}and
public class Test extends Thread
Object obj = new Object();
static int x, y;
public void run()
   synchronized(obj)
     for(;;)
      x++; y++; System.out.println(x+" "+y);
public static void main(String[] args)
   new Test().start();
   new Test().start();
In the first code example, is there a shared object between created threads and the second example, is their still a shared object between threads or is a new object created for each thread?
Cheers!

Hi,
In first case, you are acquiring lock on a static object that is of course shared (basic concept) by all instances(of Test). So, for any thread of any instance(of Test) to execute the synchronized block has to wait till any other thread of any other instance(of Test) comes out of synchronized block. It means, all the instances (of Test) are synchronized. In this scenario, you have infinite for loop within synchronized block and you are starting two threads. The thread which enters the synchronized block first will keep on executing and the other thread will never get chance to enter synchronized block.
In second case, as you are acquiring lock on an object, all the threads of a particular instance (of Test) will be synchronized. In this scenario, again you have infinite for loop within synchronized block and you are starting two threads on two different instances. Hence, both the threads will keep on executing in parallel.
I hope, you have already executed both the examples and observed output. And also hope that the above explanation will help you to understand the difference between two scenarios.
Note: Use System.out.println(Thread.currentThread().getName() + " " + x + " " + y); in your synchronized block to track which thread is printing the output.
Thanks,
Mrityunjoy

Similar Messages

  • Building Shared Object for LabView

    All;
    I'm trying to build a C++-based shared object to be called from LabView and use SunCC instead of gcc. The compile stage looks like:danny@traveler:~/tubes/dielectric/rod_software/lookup> make -f Makefile.unix suncc=1
    sunCC -I/usr/local/lv71/cintools -I/home/danny/src/NR_C301/code -c -KPIC -m32 -Di686 lookup.cc
    "/home/danny/src/NR_C301/code/interp_1d.h", line 183: Warning: n hides Base_interp::n.
    "/home/danny/src/NR_C301/code/mins_ndim.h", line 103: Warning: n hides Linemethod<extern "C" double(const NRvector<double>&)>::n.
    "lookup.cc", line 176:     Where: While instantiating "Powell<extern "C" double(const NRvector<double>&)>::minimize(const NRvector<double>&)".
    "lookup.cc", line 176:     Where: Instantiated from non-template code.
    2 Warning(s) detected.and the load stage fails like this:sunCC -G -m32 -o lookup.so lookup.o /usr/local/lv71/AppLibs/liblvrt.so.7.1 /usr/lib/libGL.so /usr/lib/libOSMesa.so.6
    /opt/sun/sunstudio12/prod/lib/crtn.o:(.text+0x0): multiple definition of `_etext'
    make: *** [lookup.so] Error 1Is my problem obvious? Is there a simple example on how to build SOs? I found the switch definitions in the Sun documentation, but no good examples yet.
    ...Dan

    If your library links to other shared libraries, use -L options to point to directories other than system directories, and the -l option for the library name after "lib".
    When building shared libraries, you also need to list all system libraries explicity, unfortunately, to ensure your library has the right dependencies.
    You should also add -zdefs to force the linker to complain about unresolved symbols. The default when building shared libraries is not to warn about them.
    You want to be sure you have included all the needed libraries in the link.
    Your link command should look like this :
    sunCC -G -m32 -o lookup.so lookup.o -zdefs \
      -L /usr/local/lv71/AppLibs -llvrt.so.7.1 -lGL.so -lOSMesa.so.6 -lCstd -lCrun -lm -lcYou don't need a -L option for /usr/lib or the directories in the Sun Studio installation. The CC driver knows where to find system libraries.
    That said, I don't think the command line issues are the cause of the multiple definition error.
    Binaries created by Sun C++ are not compatible with binaries created by other C++ compilers like g++. Is liblvrt.so.7.1 a g++ library?

  • How to create shared object in Open Vms environment.

              Hi All,
              Iam using Weblogic Server 5.1 on OpenVms 7.2-1. As a part of development, I need
              to use JNI(Java Native Interface )to call existing "C" function.
              Iam stuck at creating shared object on OpenVms. I would like to know what is the
              procedure for creating these shared objects for a given "C" programme.
              For your easy reference :This is how we create dynamic link libraries for "C"
              code by using Microsoft C++ comipler.
              cl -Ic:\jdk\include -Ic:\jdk\include\win32 -LD SampleProgramme.c -FeSampleProgramme.dll
              Can somebody help me on this?
              Thanks in Advance,
              Prashanth Bhat.
              

    You might also want to read the following series of articles:
    http://www.oracle.com/technetwork/articles/servers-storage-dev/linkinglibraries-396782.html
    Regards,
    Darryl.

  • Shared Objects and IOS 5.0+

    So, I need a straight answer. Can I use Shared Objects for my game, or will apple fail me for using them?  Will Shared Objects be backed up with iCloud?
    Thanks,
    diss.

    Boat,
    From what I have found if your IPA/APK/SWF is the same name then shared objects data should retain.
    So if version 1 of your app was
    AppleApp.ipa published from a swf by the name of AppleApp.swf
    then when you update on your final publish save your swf and .ipa under the same name
    Dont do this
    First version is
    AppleAppV1.swf published out to AppleApp.ipa
    Second version is AppleAppV2.swf published out to AppleApp.ipa
    The swf is what the shared object is associated with so keep that the same from update to update.

  • Shared Object - Prompt Data Permissions Dialog

    Hello,
    I'm creating a small app to run from CD-Rom/local
    installation that will use multiple shared objects for data
    storage. To ensure proper saving without surprising the user with a
    permissions dialog unexpectedly, I'd like to request unlimited data
    storage on first time app launch - Joey Lott shows how to do this
    in the Actionscript Cookbook...
    request=mySO.flush(1024 * 500);
    My question is,
    Can I perform this permissions request with the user a single
    time with a generic app SO in global fashion, so that the
    permissions would be set for any SOs created during the use of the
    product (all written to same SO directory), or do I have to request
    permissions for each and every SO created? Since the latter
    would be unacceptable from a UE standpoint, that means stuffing all
    app data into a single SO which doesn't seem so great from a data
    config perspective...
    I really appreciate your attention and help on this!
    Thanks in advance,
    -Maura

    Hmm. Experimented a bit and it seems that once the permission
    is set it applies to the Flash Player installation globally, and
    not per SO, not even per domain...
    Or, please correct me if I'm mistaken.
    Thanks.

  • Shared Object Location Flash Player 11

    Where is the location of Shared Objects for Flash Player 11 in Vista?

    Thanks for your reply.
    I can find those directories as you have suggested but with directory  roaming
    AppData\Roaming\Adobe.....
    AppData\Roaming\Macromedia\Flash Player\#SharedObjects...
    In Flash Player 10, it is stored in :
    AppData\Roaming\Macromedia\Flash Player\#SharedObjects...
    But when I installed Flash Player 11 and went to the site I want data  to be stored, it wasn't there (I expected the data to be stored in this directory as it did using Flash player 10) . I am just wondering if Flash Player 10 and 11 use the same folder.
    I need to know because I want to make a backup of the data , so that I can manually put them back when installing new flashplayer.
    Flash Player 11 erases  old data upon installation.

  • JRE 1.4.0 on RedHat7.1. - error... failed... cannot load shared object file

    I just installed JRE 1.4, but it doesn't work:
    failed /usr/java/j2re1.4.0/lib/i386/client/libjvm.co, because libstdc++-libc6.1.1.so.2: cannot load shared object file: no such file or directory
    When i check:
    ls /lib/libc-*
    /lib/libc/libc-2.2.2.so
    What files should I install to get it work?
    Thank you.

    The best way to explain this problem is JRE 1.4.0 is execting an old shared object for libstdc which had been updated in Redhat 7.2. Since, the functionality in libstdc should still exist in the newer version of libstc I simply made a symbolic link pointing to the current version of libstdc to satisfy JRE 1.4.0.
    ln -s /usr/lib/libstdc++-3-libc6.2-2-2.10.0.so /usr/lib/libstdc++-libc6.1-1.so.2Hope this helps.
    steve

  • Why server side shared object doesn't work for me ?

    application.onPublish = function (client, p_stream)
         var myInfo = SharedObject.get(p_stream.name);
         myInfo.setProperty("live", true);
    I set the sharedobject using code above,now I can publish video,but so is not set(from admin console, "shared object" tab).
    What can be possible reason for this?

    Change your code to below and see if it works (i mean i am not saying it will work - i am telling you to just try out - if it does not work - i'll look more into details)
    var myInfo;
    application.onPublish = function (client, p_stream)
         myInfo = SharedObject.get(p_stream.name);
         myInfo.setProperty("live", true);

  • Gardei@gardei-lab:~$ ./firefox/firefox XPCOMGlueLoad error for file /home/gardei/firefox/libxpcom.so: libxul.so: cannot open shared object file: No such file or

    Friends:
    The latest Firefox won't launch. Here's what I get...
    gardei@gardei-lab:~$ ./firefox/firefox
    XPCOMGlueLoad error for file /home/gardei/firefox/libxpcom.so:
    libxul.so: cannot open shared object file: No such file or directory
    Couldn't load XPCOM.
    Both .so files exist in ./firefox
    Thanks. -- BG

    Hello,
    Certain Firefox problems can be solved by performing a ''Clean reinstall''. This means you remove Firefox program files and then reinstall Firefox. Please follow these steps:
    '''Note:''' You might want to print these steps or view them in another browser.
    #Download the latest Desktop version of Firefox from http://www.mozilla.org and save the setup file to your computer.
    #After the download finishes, close all Firefox windows (click Exit from the Firefox or File menu).
    #Delete the Firefox installation folder, which is located in one of these locations, by default:
    #*'''Windows:'''
    #**C:\Program Files\Mozilla Firefox
    #**C:\Program Files (x86)\Mozilla Firefox
    #*'''Mac:''' Delete Firefox from the Applications folder.
    #*'''Linux:''' If you installed Firefox with the distro-based package manager, you should use the same way to uninstall it - see [[Installing Firefox on Linux]]. If you downloaded and installed the binary package from the [http://www.mozilla.org/firefox#desktop Firefox download page], simply remove the folder ''firefox'' in your home directory.
    #Now, go ahead and reinstall Firefox:
    ##Double-click the downloaded installation file and go through the steps of the installation wizard.
    ##Once the wizard is finished, choose to directly open Firefox after clicking the Finish button.
    Please report back to see if this helped you!
    Thank you.

  • Followed the download and install for firefox into my linux home directory. When launching firefox got an error message about a mission shared object. Additional detail to follow.

    When launching firefox got the following error: XPCOMGlueLoad error for file ~/firefox/libxpcom.so libxul.so cannot open shared object file: No such file or directory Couldn't load XPCOM (but file libxul.so is there) what do I do???

    Make sure that you meet the system requirements and have all required libraries installed.
    *http://www.mozilla.com/en-US/firefox/8.0.1/releasenotes/
    *http://www.mozilla.com/en-US/firefox/3.6.24/releasenotes/
    *http://kb.mozillazine.org/Installing_Firefox#Linux
    You can find the latest Firefox releases here:
    *Firefox 8.0.x: http://www.mozilla.com/en-US/firefox/all.html
    *Firefox 3.6.x: http://www.mozilla.com/en-US/firefox/all-older.html

  • Reflection objects and thread safety

    Hi,
    I believe that I saw that Field and Method objects are thread-safe (i.e., can safely have methods called against a single object instance concurrently from multiple threads), but am having trouble finding such a description in the JDK javadocs static that fact.
    I'm assuming that all thread-specific 'state' would be managed by the Object target passed to methods like invoke()/get()/set() and not on the actual Field and Method objects themselves. Ideally, i'd like to only have to look up fields and methods only once reflectively, and thereafter just use the same reflection object instances to access their target objects at runtime as a performance optimizations - possibly in different threads and at the same time - without having to pay the cost of looking it up again. I should be able to do that providing Method.invoke() is thread safe. Otherwise, i'd probably be forced to call Class.getMethod() to get a new Method object to use against each object instance, which would be more costly both from a memory standpoint (more Method objects) and a lookup-cost perspective.
    Given that lots of existing performance-critical enterprise infrastructure code, such as OR database APIs, IoC frameworks and J2EE containers use reflection to decouple the generic code from any app specific code (from a compile time perspective) as an alternative to code generation, it's surprising that there's no obvious statement about thread safety in these classes. If I look at the source code for Method, it appears to be thread safe, but I can only get so far with this analysis, as the critical code in Method appears to be implemented using a class named 'sun.reflect.MethodAccessor', whose source I don't have access to.
    I know it's possible to invoke a method against multiple objects by calling Method.invoke() against each of the target objects in question. However, there's no mention as to whether it's safe to use a single Method object instance to invoke a method against multiple target object instances at the same time (i.e., from different threads running in parallel). This would fail, for instance, if the Method object had data members that were used to communicate information between internal calls without any synchronization, as the values might be used by one thread while another was changing them.
    Just to clarify (as i've seen some confusion in other forum discussions on this topic):
    I completely understand that the thread safety of a target object's method (read, small 'm') is entirely dependent upon it's implementation and not the mechanism by which it's invoked - i.e., whether a method is invoked by an explicit compiled-in call against an instance of the target object in some Java source file, or indirectly via Method object-based reflection, is immaterial the the method's thread safety.
    What i'm asking about is the thread safety of the Method.invoke() call itself (read, big 'M'). Same question wrt Field.get()/.set() as well. These calls should be thread-safe if they're stateless wrt the Method and Field object instances that they are invoked against.

    In general, if a Java API is silent about multi-threading, it is intended to be thread-safe. See the javadoc for HashMap for an example of an explicit warning.
    It is true that Java code can have bugs that show up only on unusual implementations of the Java memory model, such as relaxed memory model machines. Most (if not all) implementations of the JDK have been deployed principally on platforms with strong memory models. (Perhaps not coincidentally, those are also the machines that have market share.) There are even bugs found occasionally in the JDK core, so draw your own conclusions about the bug-tail of our software stack on systems with relaxed memory models!
    One of the more likely bugs to run into on highly optimized systems is failure of timely initialization of non-final fields in objects which are shared in an unsynchronized manner. See http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight and related pages. JDK core programmers (at Sun, to my personal knowledge) take care not to write code with such bugs, but application programmers might.
    And, yes, caching your own Method objects is a good idea, if only because their lookup is generally cumbersome and slow. If you are very performance sensitive, you'll end up generating bytecode "shim" between your callers and the desired target methods. I expect that the http://openjdk.java.net/projects/mlvm/ (an openjdk project we are just starting) will provide some relief for this; stay tuned.
    Finally, since Method objects have no state to speak of (except their "accessible" bit, which is an ahead-of-time configuration), it would be really, really surprising if they could create a race condition of some sort. If you expect race conditions in formally stateless data structures, you are certifiably paranoid. (A normal state on some platforms, hopefully not on Java.)
    For more information about method calls, including reflective methods, see my blog post: http://blogs.sun.com/jrose/entry/anatomy_of_a_call_site
    Best wishes...

  • Confusion about shared objects...

    Hi...
    I'm building an application using JSP/Servlet technology and I've ecountered some behavior that is not that unexpected, but is something I can't seem to figure out how to get around.
    I've been using two reference manuals over the last year, to learn JSP/Servlet development and I'm not sure that either one of them, do a very good job of explaining how to avoid the problem I'm seeing. (Or maybe they do, but I'm just too dense to figure it out.)
    Both are O'Reilly manuals:
    Java Servlet Programming - Jason Humber with William Crawford
    Java Server Pages - Hans Bergsten
    Anyway, I've tried to model my application using a MVC approach.
    My controller servlet UserCtl.java is small and routes requests as a controller should.
    My business logic is in a bean. UserBean.java This object has properties that represent the fields from my UserMaster table and corresponding setter/gettter methods. It also has methods to retrieve an individual user record, insert a record, update a record, delete a record and retrieve a list of records.
    The scenario I'm experiencing is as follows:
    I bring up my application in the browser on two different PC's.
    I display the user list on each PC.
    Now...
    On each PC, I simultaneously click the Update User, selecting user 1 on pc 1 and user 2 on pc 2.
    My application then, creates a record in a lock file, for each user record. This seems to work properly, even during the simultaneous click.
    However...
    When the update form is subseqently displayed, I have a situation where the form on each of the 2 pc's contains the same data.
    I can verify that 2 different lock records were created, indicating that I did not click the same user by accident, however, the data in the form is clearly for only one of the users.
    I've read the sections over and over and I feel like I understand their comments on concurrency and how the condition I'm seeing could occur, however, I've tried many things to overcome this and nothing seems to work.
    Originally, I opened my JDBC database connection at the servlet level. I've subsequently tried doing it when I create the bean in the controller and subsequent to that, creating the connection object within the method that retrieves the user data inside the bean.
    I've tried moving all my code into functions, so that any bean variables would be localized.
    I've creating a bean from the JSP session bean object and then retrieving the record, and putting the bean back into the session object before moving to the update page.
    Note... I've also enclosed my record retrieval code within a synchronize block.
    I'm at a complete loss here. Nothing I do seems to work and I can consistently recreate this condition. Obviously, I can't move forward until I find out how to do this properly.
    I'm disappointed in the Java Server Pages book, because the author encapsulated/wrapped all of his database i/o into his own database management routines.
    This is a terrible practice for an author to perform. I understand the concept of why you would do that, however, it complicates learning the fundamentals first. I say show us how to do it the long way first, then show us how to improve on the implementation. Don't confuse an already complicated process with your own home-grown methodology.
    Anyway... I digress. Can anybody give me any pointers or recommend a good book or web based example, that can show me how to overcome the issue I am encountering? My implementation is a straightforward, simple, approach. I am trying to grasp how this stuff works, without adding in all the extra stuff like tag libraries and XSLT, etc.
    I just need to understand how to write a simple thread-safe application. I'll tackle the other stuff later. Oh... by the way... I have built the simple samples that overcome servlet class level counters that show the result differences between global variables at the servlet instance level versus reporting back localized variable values. I think that JDBC database access and/or bean creation, is more complex than that and that's where my problem is.
    Any comments, pointers, references to simple samples, will be greatly appreciated.
    Thanks,
    Brett

              You do not need a shared files system - that is just for
              convenience. You do need to have identical directory stuctures
              for all instances in the cluster.
              Mike.
              "Tomato Bug" <[email protected]> wrote:
              >
              >hi all,
              > I have a confusion with shared objects in cluster.
              > A cluster needs a shared file system to store
              > configuration
              >files and shared objects. Can I only put the shared things
              >in the
              >shared file system but not put them on the servers in
              >the cluster.
              > Thanks.
              >
              > Tomato.
              

  • Grid Control 11.1 install problem libXtst.so.6: cannot open shared object

    I have a new server installing Grid Control 11.1. Linux RHEL 5 rel 2 64 bit. Installed database 11.2.0.1 on this server (applied patch set 9352237). Installed JDK 1.6 (following note 1063587.1) and WebLogic 10.3 (note 1063112.1). When launching the Grid Control installer, I'm getting the following:
    reparing to launch Oracle Universal Installer from /tmp/OraInstall2010-05-11_12-21-44PM. Please wait ...[oracle@oracletest-100-96 gc_inst]$
    Exception in thread "main" java.lang.UnsatisfiedLinkError: /tmp/OraInstall2010-05-11_12-21-44PM/jdk/jre/lib/i386/xawt/libmawt.so: libXtst.so.6: cannot open shared object file: No such file or directory
            at java.lang.ClassLoader$NativeLibrary.load(Native Method)
            at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1778)
            at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1674)
            at java.lang.Runtime.load0(Runtime.java:770)
            at java.lang.System.load(System.java:1003)
            at java.lang.ClassLoader$NativeLibrary.load(Native Method)
            at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1778)
            at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1695)
            at java.lang.Runtime.loadLibrary0(Runtime.java:823)
            at java.lang.System.loadLibrary(System.java:1028)
            at sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:50)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.awt.Toolkit.loadLibraries(Toolkit.java:1592)
            at java.awt.Toolkit.<clinit>(Toolkit.java:1614)
            at java.awt.Font.<clinit>(Font.java:210)
            at oracle.sysman.install.oneclick.EMGCInstallStaticVariables.<clinit>(EMGCInstallStaticVariables.java:324)
            at oracle.sysman.install.oneclick.EMGCInstaller.parseCommandLineArgs(EMGCInstaller.java:503)
            at oracle.sysman.install.oneclick.EMGCInstaller.init(EMGCInstaller.java:201)
            at oracle.sysman.install.oneclick.EMGCInstaller.main(EMGCInstaller.java:992) I've checked to make sure that lixXp is installed:
    [root@oracletest]# rpm -qa --qf "%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n" | grep libXp
    libXpm-3.5.5-3.x86_64I know this is just a DISPLAYor xterm issue, but I can't figure out what the issue is. The installer for the database (11.2.0.1) in the same session launches without error. I've tried running the installer with --ignoreSysPrereqs passed and same issue.  Is there a library mismatch somewhere?  Is the installer for Grid Control that much different from that of Database 11.2.0.1 (apparently, since the database installer launches while grid control doesn't).  What obvious things am I missing in checking?
    Edited by: kellypw on May 11, 2010 11:17 AM

    I too had the same issue on linux. Check whether libXtst package is installed or not. Also, close the existing session and open a new window after the installation of the package.
    Package "libXtst (i386)" in RHEL/OEL 5 will be automatically installed with "Default RPMs" installation type. If RHEL/OEL 5 is not installed with "Default RPMs" Installation type, then please install missing package "libXtst (i386)" and then re-try.

  • Can volatile variable be called as static variable for threads?

    I am trying to understand volatile variable, and it's uses. I was thinking of using it to make it shared variable between threads, but not between object instances.
    public class VolatileExample extends Thread {
      volatile int x = 1;
      public void f() {
           x++;
           System.out.println(Integer.toString(x));
        public void run() {
              for(int i = 0; i<20;i++){
                   f();
                   try { Thread.sleep(500); } catch(InterruptedException e) {}
        }now, if I create two threads in main method of the same VolatileExample class, say T1 and T2, how many times would volatile int x be instanciated? would there be just one copy of volatile int x created, no matter howmany threads I create?

    WHICH REMINDS ME: YOU DIDN'T ANSWER MY QUESTION AS TO
    WHETHER YOU UNDERSTAND THREADS' LOCAL COPIES OF
    VARIABLES VS. THE MAIN MEM COPYIn my understanding,
    local copies means each thread gets their own copy of a variable and they play with it separately. changing this variable in one thread does not chage value for another thread.
    main mem copy is the one accessed by all the threads. If one thread changes this value, it is reflected to all other threads using this variable.
    right?
    I tried using voaltile variable as shared variable like this:
    import java.io.*;
    public class VolatileIncrement {
      private int x = 1;
      public void f() {
           x++;
           System.out.println(Integer.toString(x));
      public String toString() { return Integer.toString(x); }
      class MakeThread extends Thread{
           public MakeThread(){
                System.out.println("starting MakeThread thread");
         public void run() {
              for(int i = 0; i<20;i++){
                   f();
                   try { Thread.sleep(500); } catch(InterruptedException e) {}
      public void createT() {
         Thread T2 = new MakeThread();
              T2.start();
         Thread T1 = new MakeThread();
              T1.start();
    }and created another class:
    import java.io.*;
    class TestVolatile
         public static void main(String[] args)
              VolatileIncrement vi = new VolatileIncrement();
              System.out.println("creating threads now...");
              vi.createT();
              System.out.println("Done Testing!!");
    }can this be called as correctly using non-static volatile variable as shared data?

Maybe you are looking for