How to create object per thread

Hi everyone,
This is my problem. I want to have a static method. Inside of it I want to add an element into a List, let's say I want to track something by doing this. But I also want this List to have multiple copies depending on threads, which means for every call to this static method, I want to call the "add" method on different List objects depending which thread it is from.
Does it make sense? Do I need to have a thread pool to keep those thread references or something?
How about I use Thread.currentThread() to determine whether this call is from a different thread so that I create another List?
Thank you very much!
Edited by: feiya200 on Feb 26, 2008 10:31 PM

want to be perfect with singleton as why it is needed and how it works so see this by [email protected], Bijnor
For those who haven't heard of design patterns before, or who are familiar with the term but not its meaning, a design pattern is a template for software development. The purpose of the template is to define a particular behavior or technique that can be used as a building block for the construction of software - to solve universal problems that commonly face developers. Think of design code as a way of passing on some nifty piece of advice, just like your mother used to give. "Never wear your socks for more than one day" might be an old family adage, passed down from generation to generation. It's common sense solutions that are passed on to others. Consider a design pattern as a useful piece of advice for designing software.
Design patterns out of the way, let's look at the singleton. By now, you're probably wondering what a singleton is - isn't jargon terrible? A singleton is an object that cannot be instantiated. At first, that might seem counterintuitive - after all, we need an instance of an object before we can use it. Well yes a singleton can be created, but it can't be instantiated by developers - meaning that the singleton class has control over how it is created. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy.
So why would this be useful? Often in designing a system, we want to control how an object is used, and prevent others (ourselves included) from making copies of it or creating new instances. For example, a central configuration object that stores setup information should have one and one only instance - a global copy accessible from any part of the application, including any threads that are running. Creating a new configuration object and using it would be fairly useless, as other parts of the application might be looking at the old configuration object, and changes to application settings wouldn't always be acted upon. I'm sure you can think of a other situations where a singleton would be useful - perhaps you've even used one before without giving it a name. It's a common enough design criteria (not used everyday, but you'll come across it from time to time). The singleton pattern can be applied in any language, but since we're all Java programmers here (if you're not, shame!) let's look at how to implement the pattern using Java.
Preventing direct instantiation
We all know how objects are instantiated right? Maybe not everyone? Let's go through a quick refresher.
Objects are instantiated by using the new keyword. The new keyword allows you to create a new instance of an object, and to specify parameters to the class's constructor. You can specify no parameters, in which case the blank constructor (also known as the default constructor) is invoked. Constructors can have access modifiers, like public and private, which allow you to control which classes have access to a constructor. So to prevent direct instantiation, we create a private default constructor, so that other classes can't create a new instance.
We'll start with the class definition, for a SingletonObject class. Next, we provide a default constructor that is marked as private. No actual code needs to be written, but you're free to add some initialization code if you'd like.
public class SingletonObject
     private SingletonObject()
          // no code req'd
So far so good. But unless we add some further code, there'll be absolutely no way to use the class. We want to prevent direct instantiation, but we still need to allow a way to get a reference to an instance of the singleton object.
Getting an instance of the singleton
We need to provide an accessor method, that returns an instance of the SingletonObject class but doesn't allow more than one copy to be accessed. We can manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). To do this, provide a public static method called getSingletonObject(), and store a copy of the singleton in a private member variable.
public class SingletonObject
private SingletonObject()
// no code req'd
public static SingletonObject getSingletonObject()
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
private static SingletonObject ref;
So far, so good. When first called, the getSingletonObject() method creates a singleton instance, assigns it to a member variable, and returns the singleton. Subsequent calls will return the same singleton, and all is well with the world. You could extend the functionality of the singleton object by adding new methods, to perform the types of tasks your singleton needs. So the singleton is done, right? Well almost.....
Preventing thread problems with your singleton
We need to make sure that threads calling the getSingletonObject() method don't cause problems, so it's advisable to mark the method as synchronized. This prevents two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. To change the method, just add the synchronized keyword as follows to the method declaration :-
public static synchronized
     SingletonObject getSingletonObject()
Are we finished yet?
There, finished. A singleton object that guarantees one instance of the class, and never more than one. Right? Well.... not quite. Where there's a will, there's a way - it is still possible to evade all our defensive programming and create more than one instance of the singleton class defined above. Here's where most articles on singletons fall down, because they forget about cloning. Examine the following code snippet, which clones a singleton object.
public class Clone
     public static void main(String args[])
     throws Exception
     // Get a singleton
     SingletonObject obj =
     SingletonObject.getSingletonObject();
     // Buahahaha. Let's clone the object
     SingletonObject clone =
          (SingletonObject) obj.clone();
Okay, we're cheating a little here. There isn't a clone() method defined in SingletonObject, but there is in the java.lang.Object class which it is inherited from. By default, the clone() method is marked as protected, but if your SingletonObject extends another class that does support cloning, it is possible to violate the design principles of the singleton. So, to be absolutely positively 100% certain that a singleton really is a singleton, we must add a clone() method of our own, and throw a CloneNotSupportedException if anyone dares try!
Here's the final source code for a SingletonObject, which you can use as a template for your own singletons.
public class SingletonObject
private SingletonObject()
// no code req'd
public static SingletonObject getSingletonObject()
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();          
return ref;
public Object clone()
     throws CloneNotSupportedException
throw new CloneNotSupportedException();
// that'll teach 'em
private static SingletonObject ref;
Summary
A singleton is an class that can be instantiated once, and only once. This is a fairly unique property, but useful in a wide range of object designs. Creating an implementation of the singleton pattern is fairly straightforward - simple block off access to all constructors, provide a static method for getting an instance of the singleton, and prevent cloning.
What is a singleton class?
A: A class whose number of instances that can be instantiated is limited to one is called a singleton class. Thus, at any given time only one instance can exist, no more.
Q: Can you give me an example, where it is used?
A: The singleton design pattern is used whenever the design requires only one instance of a class. Some examples:
�     Application classes. There should only be one application class. (Note: Please bear in mind, MFC class 'CWinApp' is not implemented as a singleton class)
�     Logger classes. For logging purposes of an application there is usually one logger instance required.
Q: How could a singleton class be implemented?
A: There are several ways of creating a singleton class. The most simple approach is shown below:
Code:
class CMySingleton
public:
static CMySingleton& Instance()
static CMySingleton singleton;
return singleton;
// Other non-static member functions
private:
CMySingleton() {}; // Private constructor
CMySingleton(const CMySingleton&); // Prevent copy-construction
CMySingleton& operator=(const CMySingleton&); // Prevent assignment
Can I extend the singleton pattern to allow more than one instance?
A: The general purpose of the singleton design pattern is to limit the number of instances of a class to only one. However, the pattern can be extended by many ways to actually control the number of instances allowed. One way is shown below...
class CMyClass
private:
CMyClass() {} // Private Constructor
static int nCount; // Current number of instances
static int nMaxInstance; // Maximum number of instances
public:
~CMyClass(); // Public Destructor
static CMyClass* CreateInstance(); // Construct Indirectly
//Add whatever members you want
};

Similar Messages

  • How to create objects in ABAP Webdynpro?

    Hi,
    I want to create the object for the class: <b>CL_GUI_FRONTEND_SERVICES.</b>
    then i want to call file_save_dialog method.
    how shoud i write the code, plz?

    I have written this code:
    v_guiobj TYPE REF TO cl_gui_frontend_services.
    <u> ?????????????</u>
    v_guiobj->file_save_dialog( ...).
    How to create object in the place of ?????????????.
    Bcoz, when i run this i am getting:
    <b>Access via Null object reference not possible.</b>

  • How to create object at infoview

    Hi all
    i am using SAP BO 3.1
    How to create object called SL NO this is not available at universe and second object  "code" is coming from universe.
    final output should be like this
    SL NO
    code
    1
    Non-Emergency ED Utilization
    2
    Office Visits
    3
    Inpatient Stays
    thanks in advance!!
    Ranjeet

    Hi Ranjeet
    Insert one column in that report. Write formula like this...
    =LineNumber()-1
    Regards,
    G

  • How to create objects in stack

    I am working on Weblogic 10 and JDK 1.5. In Java the objects are always created in heap. Can anybody tell me how to create objects in stack?

    SKMoharana wrote:
    i need objects to be allocated in stack as my application should respond in real time (time predictable).I heard this is possible in Mustang.If I am understanding you correctly, allocating objects on the stack will not help you, and creating objects on the heap will not hurt you.
    It is provably impossible to create a truly time predictable application (in any language), so what you're really looking to do is create a program that responds acceptably quickly for an acceptable percentage of the time. For this you can create benchmarks like "responds in 250 milliseconds or less 99.5% of the time".
    To this end, you could create a prototype program that creates the objects you wish on the heap, and see if there actually is a problem. Don't fall into the trap of premature optimization.
    Even if you do discover that your object creation IS the problem, heap allocation is not the problem. Take a look at this article. It takes ten machine instructions, less than 1 millisecond, to allocate an object.
    Your performance problems are most likely in the object initialization (look for long loops or deep recursions), the display (if this is a GUI application), or your network connection (if this is a web application).

  • How to create objects to paint itselfs without specifiy the location

    How to create objects to paint itselfs without specifiy the location using Java 2D

    shot in the dark: pass in the Graphics2D context to the method ?

  • How to create object for a interface (or) how to use ITextModel Interface

    Hi,
    I am new to vc++ and indesign, i am using windows xp as OS and Indesign CS3 as version, now i want to know how to create an object for the ITextModel Interface (or) how to use the ITextModel interface, for getting the selected text and to manipulate the content, for this i tried myself to the best for more than a week,
    but i not get any solution or any idea to do it, so i post this scrap, if any one knows kindly help me immediately, if u want any more details kindly reply me i am ready to give..
    Regards,
    ram

    Hi, Ram,
    as Jongware already has explained in a previous thread, this is the scripting forum, the SDK forum is next door.
    Besides, your question has already been answered over there in SDK forum - with a reference to an existing example, including documented source. There is also plenty more documentation (780 pages alone in the programming guide) and other working examples.
    The brief response was a perfect match to the vague, general scope of the question. If you want more details, be more specific yourself. Do not just touch such major topics as selection, text, object architecture in one sentence to expect a silver bullet. Instead, stick to one detail, find and read the relevant examples and documentation (did I mention the programming guide?) yourself e.g. using keyword search. Quote your code where you're stuck.
    Being new to both VC++ and InDesign is an explanation but no excuse. IMO, same goes for "using windows xp as OS". All together are bad starting conditions if you intend to write a plugin. Even a seasoned C++ programmer with some years of experience in publishing quirks will easily require months, so don't become impatient after just a week.
    If you need quick results and have a programming background such as a recent Java101, reconsider scripting (this forum). It can bring you amazingly far and you'll learn InDesign through a simplified object model. Same principles apply - there is plenty documentation and a good choice of examples.
    Regards,
    Dirk

  • How to create a new thread in display function -----Java OpenGL

    use netbean 6.1 to do this work.
    public void display(GLAutoDrawable drawable) {
          GL  gl = drawable.getGL();
          //I want to create a new thread here to draw an object
          Thread dt = new Thread(new DrawThread(gl,2),"Thread0");    //create a thread,DrawThread is a class I define
          //but it failed when compiling
          //are there any other ways or how to improve my method?
    }I want to do like this because I do not like to block the main thread when it is drawing an object

    Well, the autocode in your application is maintained by your autocode module, any attempt at changing it will result in having it reset back to the original autocode--that's one of the gotcha's about using autocode.
    Since it looks like you may not have the skills to do what you are asking and relying on the autocoder, you should probably start here:
    [Java Tutorial|http://java.sun.com/docs/books/tutorial/]
    And stay there until you are comfortable coding for yourself.

  • How to create objects dynamically (with dynamic # of parameters)

    I need to create a set of objects based on a definition from an XML file (obtained from the server) and add them to my scene.
    I understand how to create the object using getDefinitionByName (and the limitations regarding classes needing to be referenced to be loaded into the SWF).
    But some objects require parameters for the constructor, and some don't. The XML can easily pass in the required parameter information, but I can't figure out how to create a new object with a dynamic set of arguments (something akin to using the Function.call(obj, argsArray) method.
    For example, I need something like this to work:
    var mc=new (getDefinitionByName(str) as Class).call(thisNewThing, argsArray)
    Currently this is as far as I can get:
    var mc=new (getDefinitionByName(str) as Class)(static, list, of, arguments)
    Thoughts?

    I think what Dave is asking is a bit different.
    He's wanting to know how to invoke the constructor of an object dynamically (when he only knows the # of constructor arguments at runtime).
    This class I know will do it but seems to be a hack:
    http://code.google.com/p/jsinterface/source/browse/trunk/source/core/aw/utils/ClassUtils.a s?spec=svn12&r=12
    See the 'call' method, which first counts the # of arguments then invokes one of 'n' construction methods based on the number of constructor args.
    I've yet to find a clean AS3 way of doing things ala 'call' though.
    -Corey

  • How to create object in sproxy--

    Hi  all
    i am new to XI
    how to create a new object in sproxy transction
    there is no such option called create in sproxy transction , i can only see a option called edit object
    kindly hepl me out , to create new object in spoxy.

    Hi,
    What do you mean by create a new object in the proxy?
    Means you want to generate the proxy class?
    if yes then we have two proxies
    1. Client Proxy: If the sender is R/3 then we have to create the client proxy, by using one SE38 program we can call this proxy
    2. Server Proxy: If the R/3 is at receiver side then we call this as server proxy. it executes by itself.
    Client proxy:
    /people/ravikumar.allampallam/blog/2005/03/14/abap-proxies-in-xiclient-proxy
    Server Proxy:
    /people/siva.maranani/blog/2005/04/03/abap-server-proxies
    Proxy generation
    http://help.sap.com/saphelp_nw04/helpdata/en/ba/d4c23b95c8466ce10000000a114084/content.htm
    If you create the Service interface or message interface in the XI/PI then that interface we can view in the R/3 system when we execute the SPROXY transaction.
    Regards
    Ramesh

  • How to create a new thread/TimerTask in oc4j 10.1.2

    Hi,
    I want to create a TimerTask / Thread in oc4j 10.1.2 so its ejb2.0 no Timer Beans.
    I know its not good to create my own custom TimerTask/Threads inside a container, so i looked and i saw that oc4j 10.1.2 has the notion of "2.9.2 Thread Pool Settings" however this refers only to:
    cite:
    +"The worker thread pool contains worker threads used in processing RMI , HTTP and AJP requests, as well as MDB listener threads. These are process-intensive and use database resources. "+
    but i dont do any rmi/http/ajp/mdb i just want a simple java TimerTask or a Thread.
    Can anyone assist me how to achieve this creating of timerTask / threads with oc4j 10.1.2 ejb2.0?
    Thanks

    Hi
    Since the error points to the unavailability of the driver class,can you double check your library claspath entries again.
    I just tried a DB2 connection using the following properties and the connection went through fine:
    Driver class name: com.oracle.ias.jdbc.db2.DB2Driver
    URL: jdbc:merant:db2://<host_name>:50000;DatabaseName=SAMPLE
    Thanks
    Prasanth

  • How to create object by getting class name as input

    hi
    i need to create object for the existing classes by getting class name as input from the user at run time.
    how can i do it.
    for exapmle ExpnEvaluation is a class, i will get this class name as input and store it in a string
    String classname = "ExpnEvaluation";
    now how can i create object for the class ExpnEvaluation by using the string classname in which the class name is storted
    Thanks in advance

    i think we have to cast it, can u help me how to cast
    the obj to the classname that i get as inputThat's exactly the point why you shouldn't be doing this. You can't have a dynamic cast at compile time already. It doesn't make sense. Which is also the reason why class.forName().newInstance() is a very nice but also often very useless tool, unless the classes loaded all share a mutual interface.

  • How to create ApplicationModule inside Thread!

    I would like to create an ApplicationModule object inside Thread! When I create an ApplicationModule anywhere else in class it works fine with no problem.
    But when I put ApplicationModule am = Configuration.createRootApplicationModule("",""); inside Thread (...in Run() method ) It throws the error:
    oracle.jbo.JboException: JBO-33001: Cannot find the configuration file /package/model/common/bc4j.xcfg in the classpath at oracle.jbo.client.Configuration.loadFromClassPath(Configuration.java:358)
         at oracle.jbo.common.ampool.PoolMgr.createPool(PoolMgr.java:281)
         at oracle.jbo.common.ampool.PoolMgr.findPool(PoolMgr.java:482)
         at oracle.jbo.common.ampool.ContextPoolManager.findPool(ContextPoolManager.java:165)
         at oracle.jbo.client.Configuration.createRootApplicationModule(Configuration.java:1457)
         at oracle.jbo.client.Configuration.createRootApplicationModule(Configuration.java:1435)
         at hrm.edc.model.pripravaPodatkov.ZajemPodatkov.run(ZajemPodatkov.java:56)
         at java.lang.Thread.run(Thread.java:534)
    If Anyone have a solution please help!
    Thanks!

    Cannot find the configuration file /package/model/common/bc4j.xcfg in the classpath
    In the client/view project set a dependency to the BC4J project.

  • How to create object[][] dinamically

    I know that if I want to create object[][] I have to do something like this
    Object[][] obj = new Object[3][4];
    but I don't know how long my obj is... what can I do? I'd like to do something like new object[][]; like arraylist or something like that
    thanks a lot

    Well, I have a db and some query on it... so I won't know how many rows there are... Maybe the best solution is the first one (ArrayList Of ArrayList).
    Thanks to all of you

  • How to create Object related messages using cl_bsp_wd_message_service?

    Hi Gurus,
    Can any ony explain how to create the object related messages using add_message method of cl_bsp_wd_message_service?
    Thanks,
    Murali.

    Hi Murali,
    Check the below code .. hope it helps..
      DATA lr_msg_service     TYPE REF TO cl_bsp_wd_message_service.
      DATA lr_exception       TYPE REF TO cx_root.
      DATA lr_rtti            TYPE REF TO cl_abap_objectdescr.
      DATA lv_msg_type        TYPE        symsgty.
      DATA lv_msg_id          TYPE        symsgid.
      DATA lv_msg_number      TYPE        symsgno.
      DATA lv_msg_v1          TYPE        symsgv.
      DATA lv_msg_v2          TYPE        symsgv.
      DATA lv_msg_v3          TYPE        symsgv.
      DATA lv_msg_v4          TYPE        symsgv.
      DATA lv_msg_level       TYPE        bsp_wd_message_level.
      DATA lr_verification    TYPE REF TO if_bsp_wd_message_handler."#EC NEEDED
      DATA lv_important_info  TYPE        abap_bool.
      DATA lv_exc_prog_name   TYPE        syrepid.
      DATA lv_exc_incl_name   TYPE        syrepid.
      DATA lv_exc_src_line    TYPE        i.
      lr_exception = ir_exception.
    drill down to first exception
      WHILE lr_exception->previous IS BOUND.
        lr_exception = lr_exception->previous.
      ENDWHILE.
      lr_rtti ?= cl_abap_typedescr=>describe_by_object_ref( p_object_ref = lr_exception ).
      lr_exception->get_source_position( IMPORTING program_name = lv_exc_prog_name
                                                   include_name = lv_exc_incl_name
                                                   source_line  = lv_exc_src_line ).
    prepare message
      lr_msg_service = cl_bsp_wd_message_service=>get_instance( ).
      lv_msg_type   = if_genil_message_container=>mt_warning.
      lv_msg_id     = 'CRM_IC_APPL'.
      lv_msg_number = '003'.
      lv_msg_v1     = lr_rtti->get_relative_name( ).
      lv_msg_v2     = ir_exception->get_text( ).
      lv_msg_v3     = lv_exc_incl_name.
      lv_msg_v4     = lv_exc_src_line.
      lv_msg_level  = '9'.
    add message to error log
      lr_msg_service->add_message(
          iv_msg_type       = lv_msg_type
          iv_msg_id         = lv_msg_id
          iv_msg_number     = lv_msg_number
          iv_msg_v1         = lv_msg_v1
          iv_msg_v2         = lv_msg_v2
          iv_msg_v3         = lv_msg_v3
          iv_msg_v4         = lv_msg_v4
          iv_msg_level      = lv_msg_level
          iv_verification   = lr_verification
          iv_important_info = lv_important_info ).
    Regards,
    Raghu

  • How to create Object!

    Hi all,
            Can anyone tell me how to create an object of the class CL_BP_HEAD_CORPACCOUNTDET_CTXT .
    Please reply as fast as possible.
    Regards,
    Vijay

    Hi Balasubramanian,
    The below steps might help u out.
    1.      Call the function Create Object.
    You have the following options:
    ¡        Choose Object ->New () in the main menu (or the pushbutton Create Object ).
    ¡        Position the cursor on a structure node in the navigation area and choose New () from the context menu.
    In this case, there are already entries in the Create Object dialog, corresponding to the position of the cursor in the navigation area.
    Integration Builder (Integration Directory): You have positioned the cursor on the Service node of a communication party. If you call the function Create Object from the context menu, there are already entries for the object type Service and the party field.
    You cannot create objects of type RFC or IDoc again.
           2.      Enter the required information. Select the object type first and then specify the object key.
    An input help  is available to help you specify the key values. To call the input help, use the icon . The value selection offered by the input help may depend on which values have already been defined for the other key attributes.
    Integration Builder (Integration Repository): The namespace selection depends on the selected software component version.
           3.      To confirm your entries, choose Create.
    This calls the object editor for this object. The specifications that you made when you created the object are displayed in the header. You can edit the object further in the work area of the object editor.
    Once you have confirmed your entries by choosing Create in the Create Object dialog, you can no longer change the object key.
    Reward if helpful.
    Thankyou,
    Regards.

Maybe you are looking for