Is Clone thread safe?

I am examining property change class and notice that it does an unsynchronized clone of vector. This makes me wonder if clone is thread safe? it must be or this clone could experience the same problems of copying the vector while its being modified.
Anybody know if clone is indeed thread safe?

Of course your clone() method can be thread safe if
you want it to be; simply make your overriding clone() method
synchronized ...I still don't think this will be thread-safe, unless all methods that
change data in the object are also synchronized. Even then you can't
be sure unless you declare your class final, because otherwise
someone else could add non-threadsafe methods later.Sure, that's why I emphasised '*your* clone() method'. What others
do to it is up to them ;-)
kind regards,
Jos

Similar Messages

  • Need thread safe way to access read-only objects

    I have been working on a lot of projects and all the developers agree that they want thread safe code when called by many threads. It's rare developers are making statement like: "Data are not corrupted often so don't bother" or "It's not thread safe, but that will not often create issues".
    In TopLink client session itself is thread safe but not the persistent object themselves. Via client session, if you want thread safe access you need to put a lock on CacheKey and it's not a public/supported API. So the only thread safe access is via unit of work.
    We would like fast access to objects. We have a batch process that just need read-only access to objects. We need to read via unit of work to get thread safe access. But we just need the clone when we read via unit of work, we don't need the backup for change detection.
    However, TopLink doesn't have a mean to do that.
    Please push implementation of Bug5998333[WANT THREAD SAFE AND CORRECT ISOLATION WITH OBJECTS FROM ADDREADONLYCLASS]
    In Hibernate, by design, all access are always thread safe. Accessing read-only object just create one copy (a clone), no backup needed.
    Oracle claims that TopLink is fast. I wonder if their performance testing code is thread safe, so access objects via unit of work or they take the shortcut of accessing objects from client session. Also, reliable performance comparison should use conform in unit of work.

    As you stated the UnitOfWork offers you your desired functionality, you would just like an improvement in performance.
    In TopLink 10.1.3 (or 11g preview) you have a few options:
    - Use a UnitOfWork an live with the slight overhead of the back copies (it will only add 5-30 % overhead to your processing)
    - Instead use an isolated client session, this will not require any cloning or backup clones, but also does not allow any caching.
    - Use change tracking, TopLink added attribute-level change tracking in 10.1.3, when used the UnitOfWork does not create backup clones. In 10.1.3 it was mainly used for CMP and requires code generation, but you could implement or weave the code yourself. In TopLink 11g, change tracking is weaved by default with JPA and the weaver can also be used with POJO objects.
    I agree that having a feature to mark an object as transactionally read-only would be desirable, it seems like you have logged the enhancement. You could try escalting the enhancement through Oracle support, but since it is an enhancement and not a bug, it is probably beyond what support offers. You may wish to investigate services, or potentially join the open source Eclipse EclipseLink project which the next version of TopLink is being developed under and take part in the feature yourself.

  • Is Outside In's PDF Export library's function EXOpenExport thread-safe?

    I'm writing a C++ wrapper, for Node.js, around the Outside In PDF Export library, on Ubuntu Linux. Node.js has a single threaded event loop and therefor any long-running processing is done on a worker thread. So, my wrapper is calling all of the PDF Export methods inside of this worker thread. I mention this so that you can be sure of two things: this is a threaded environment, and all PDF Export functions are being called on the same worker thread. Also, I am not making use of any redirected IO or PDF Export-handled threading. I've initialized the library specifying to use no threads. So all of this processing should be occuring within the thread that I call the functions on.
    Everything seems to go fine when exporting a single PDF or even maybe two or three in quick succession. When I up the number of PDFs that I try to export to 5+, I receive a SIGSEGV segementation fault from within the OIT libs. The back trace is below:
    Program received signal SIGSEGV, Segmentation fault.
    [Switching to Thread 0x7ffff4fd0700 (LWP 1577)]
    0x00007fffeef1da26 in HandlePoolCreateHandle () from /usr/local/lib/pdfexport/libwv_core.so
    (gdb) bt
    #0 0x00007fffeef1da26 in HandlePoolCreateHandle () from /usr/local/lib/pdfexport/libwv_core.so
    #1 0x00007fffeef1925d in Win32VCreateHandle () from /usr/local/lib/pdfexport/libwv_core.so
    #2 0x00007fffed49046b in WrapBrush(void*, GdiBrush*) () from /usr/local/lib/pdfexport/libos_pdf.so
    #3 0x00007fffed46e8c8 in ?? () from /usr/local/lib/pdfexport/libos_pdf.so
    #4 0x00007fffed46df63 in GNGetOutputSolutionInfoAt () from /usr/local/lib/pdfexport/libos_pdf.so
    #5 0x00007fffeef1e32a in ?? () from /usr/local/lib/pdfexport/libwv_core.so
    #6 0x00007fffeef1e214 in ?? () from /usr/local/lib/pdfexport/libwv_core.so
    #7 0x00007fffeef18ed3 in Win32VLoadOS () from /usr/local/lib/pdfexport/libwv_core.so
    #8 0x00007fffeddffb24 in VwExportOpen () from /usr/local/lib/pdfexport/libex_pagelayout.so
    #9 0x00007ffff4062c4d in FAOpenExport () from /usr/local/lib/pdfexport/libsc_fa.so
    #10 0x00007ffff7e53270 in EXOpenExport () from /usr/local/lib/pdfexport/libsc_ex.so
    #11 0x00007ffff43c0a4d in topdf_convert(uv_work_s*) ()
    from /home/ryan/repos/pdf-service/node_modules/topdf/build/Release/topdf.node
    #12 0x00000000006e2ec7 in worker (arg=<optimized out>) at ../deps/uv/src/unix/threadpool.c:65
    #13 0x00007ffff6fa6e9a in start_thread () from /lib/x86_64-linux-gnu/libpthread.so.0
    #14 0x00007ffff6cd3cbd in clone () from /lib/x86_64-linux-gnu/libc.so.6
    #15 0x0000000000000000 in ?? ()
    I'll explain the back trace a little. The function on #11 is the function inside my code. That is the function in which I call all of the OIT lib functions. The functions on lines #12 and higher are the Node.js-related threading functions, setting up the thread to run my code's function. Functions on lines #10 down to #1 are all the OIT-called functions.
    In the documentation for PDF Export, it says that if you're going to be using this library inside a threaded environment, then you need to call the init and deinit functions each time within the worker thread. I'm doing this in my code, which you can see here: https://github.com/ryancole/topdf/blob/master/src/topdf.cc#L29-L74
    Is there anything else that I need to be setting that would cause this? I'm only specifying the font directory, explicitly. Are these libraries actually thread-safe? It doesn't look like they are.

    Well, upon receiving a second opinion on the meaning of the phrasing in the documentation, I have got the library working in a threaded environment now. The first parameter to DEInitEx was supposed to specify to enable PTHREAD support, which I did not have. I thought that it meant something other than it actually does.

  • SSRS - Is there a multi thread safe way of displaying information from a DataSet in a Report Header?

     In order to dynamically display data in the Report Header based in the current record of the Dataset, we started using Shared Variables, we initially used ReportItems!SomeTextbox.Value, but we noticed that when SomeTextbox was not rendered in the body
    (usually because a comment section grow to occupy most of the page if not more than one page), then the ReportItem printed a blank/null value.
    So, a method was defined in the Code section of the report that would set the value to the shared variable:
    public shared Params as String
    public shared Function SetValues(Param as String ) as String
    Params = Param
    Return Params 
    End Function
    Which would be called in the detail section of the tablix, then in the header a textbox would hold the following expression:
    =Code.Params
    This worked beautifully since, it now didn't mattered that the body section didn't had the SetValues call, the variable persited and the Header displayed the correct value. Our problem now is that when the report is being called in different threads with
    different data, the variable being shared/static gets modified by all the reports being run at the same time. 
    So far I've tried several things:
    - The variables need to be shared, otherwise the value set in the Body can't be seen by the header.
    - Using Hashtables behaves exactly like the ReportItem option.
    - Using a C# DLL with non static variables to take care of this, didn't work because apparently when the DLL is being called by the Body generates a different instance of the DLL than when it's called from the header.
    So is there a way to deal with this issue in a multi thread safe way?
    Thanks in advance!
     

    Hi Angel,
    Per my understanding that you want to dynamic display the group data in the report header, you have set page break based on the group, so when click to the next page, the report hearder will change according to the value in the group, when you are using
    the shared variables you got the multiple thread safe problem, right?
    I have tested on my local environment and can reproduce the issue, according to the multiple safe problem the better way is to use the harshtable behaves in the custom code,  you have mentioned that you have tryied touse the harshtable but finally got
    the same result as using the ReportItem!TextBox.Value, the problem can be cuased by the logic of the code that not works fine.
    Please reference to the custom code below which works fine and can get all the expect value display on every page:
    Shared ht As System.Collections.Hashtable = New System.Collections.Hashtable
    Public Function SetGroupHeader( ByVal group As Object _
    ,ByRef groupName As String _
    ,ByRef userID As String) As String
    Dim key As String = groupName & userID
    If Not group Is Nothing Then
    Dim g As String = CType(group, String)
    If Not (ht.ContainsKey(key)) Then
    ' must be the first pass so set the current group to group
    ht.Add(key, g)
    Else
    If Not (ht(key).Equals(g)) Then
    ht(key) = g
    End If
    End If
    End If
    Return ht(key)
    End Function
    Using this exprssion in the textbox of the reportheader:
    =Code.SetGroupHeader(ReportItems!Language.Value,"GroupName", User!UserID)
    Links belowe about the hashtable and the mutiple threads safe problem for your reference:
    http://stackoverflow.com/questions/2067537/ssrs-code-shared-variables-and-simultaneous-report-execution
    http://sqlserverbiblog.wordpress.com/2011/10/10/using-custom-code-functions-in-reporting-services-reports/
    If you still have any problem, please feel free to ask.
    Regards
    Vicky Liu

  • How can I use a Selector in a thread safe way?

    Hello,
    I'm using a server socket with a java.nio.channels.Selector contemporarily by 3 different threads (this number may change in the future).
    From the javadoc: Selectors are themselves safe for use by multiple concurrent threads; their key sets, however, are not.
    Following this advise, I wrote code in this way:
             List keys = new LinkedList(); //private key list for each thread
             while (true) {
              keys.clear();
              synchronized(selector) {
                  int num = selector.select();
                  if (num == 0)
                   continue;
                  Set selectedKeys = selector.selectedKeys();
                  //I expected this code to produce disjoint key sets on each thread...
                  keys.addAll(selectedKeys);
                  selectedKeys.clear();
              Iterator it = keys.iterator();
              while (it.hasNext()) {
                  SelectionKey key = (SelectionKey) it.next();
                  if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
                   Socket s = serverSocket.accept();
                   SocketChannel sc = s.getChannel();
                   sc.configureBlocking( false );
                   sc.register( selector, SelectionKey.OP_READ );
                  } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
    //.....Unfortunately synchronizing on the selector didn't have the effect I expected. When another thread select()s, it sees the same key list as the other thread that select()ed previously. When control arrives to serverSocket.accept(), one thread goes ahead and the other two catch an IllegalBlockingModeException.
    I'm not willing to handle this exception, the right thing to do is giving disjoint key sets to each thread. How can I achieve this goal?
    Thanks in advance

    A single thread won't be enough cause after reading data from the socket I do some processing on it that may take long.So despatch that processing to a separate thread.
    Most of this processing is I/O boundI/O bound on the socket? or something else? If it's I/O bound on the socket that's even more of a reason to use a single thread.
    Anyway I think I'll use a single thread with the selector, put incoming data in a queue and let other 2 or 3 threads read from it.Precisely. Ditto outbound data.
    Thanks for your replies. But I'm still curious: why is a selector thread safe if it can't be used with multiple threads because of it's semantics?It can, but there are synchronization issues to overcome (with Selector.wakeup()), and generally the cost of solving these is much higher than the cost of a single-threaded selector solution with worker threads for the application processing.

  • Is the Illustrator SDK thread-safe?

    After searching this forum and the Illustrator SDK documentation, I can't find any references to a discussion about threading issues using the Illustrator C++ SDK. There is only a reference in some header files as to whether menu text is threaded, without any explanation.
    I take this to mean that probably the Illustrator SDK is not "thread-safe" (i.e., it is not safe to make API calls from arbitrary threads; you should only call the API from the thread that calls into your plug-in). Does anyone know this to be the case, or not?
    If it is the case, the normal way I'd write a plug-in to respond to requests from other applications for drawing services would be through a mutex-protected queue. In other words, when Illustrator calls the plug-in at application startup time, the plug-in could set up a mutually exclusive lock (a mutex), start a thread that could respond to requests from other applications, and request periodic idle processing time from the application. When such a request arrived from another application at an arbitrary time, the thread could respond by locking the queue, adding a request to the queue for drawing services in some format that the plug-in would define, and unlocking the queue. The next time the application called the plugin with an idle event, the queue could be locked, pulled from, and unlocked. Whatever request had been pulled could then be serviced with Illustrator API calls. Does anyone know whether that is a workable strategy for Illustrator?
    I assume it probably is, because that seems to be the way the ScriptingSupport.aip plug-in works. I did a simple test with three instances of a Visual Basic generated EXE file. All three were able to make overlapping requests to Illustrator, and each request was worked upon in turn, with intermediate results from each request arriving in turn. This was a simple test to add some "Hello, World" text and export some jpegs,
    repeatedly.
    Any advice would be greatly appreciated!
    Glenn Picher
    Dirigo Multimedia, Inc.
    [email protected]

    Zac Lam wrote:
    The Memory Suite does pull from a specific memory pool that is set based on the user-specified Memory settings in the Preferences.  If you use standard OS calls, then you could end up allocating memory beyond the user-specified settings, whereas using the Memory Suite will help you stick to the Memory settings in the Preferences.
    When you get back NULL when allocating memory, are you hitting the upper boundaries of your memory usage?  Are you getting any error code returned from the function calls themselves?
    I am not hitting the upper memory bounds - I have several customers that have 10's of Gb free.
    There is no error return code from the ->NewPtr() call.
         PrMemoryPtr (*NewPtr)(csSDK_uint32 byteCount);
    A NULL pointer is how you detect a problem.
    Note that changing the size of the ->ReserveMemory() doesn't seem to make any difference as to whether you'll get a memory ptr or NULL back.
    btw my NewPtr size is either
         W x H x sizeof(PrPixelFormat_YUVA4444_32f)
         W x H x sizeof(PrPixelFormat_YUVA4444_8u)
    and happens concurrently on #cpu's threads (eg 16 to 32 instances at once is pretty common).
    The more processing power that the nVidia card has seems to make it fall over faster.
    eg I don't see it at all on a GTS 250 but do on a GTX 480, Quadro 4000 & 5000 and GTX 660
    I think there is a threading issue and an issue with the Memory Suite's pool and how it interacts with the CUDA memory pool. - note that CUDA sets RESERVED (aka locked) memory which can easily cause a fragmenting problem if you're not using the OS memory handler.

  • Is the Memory Suite thread safe?

    Hi all,
    Is the memory suite thread safe (at least when used from the Exporter context)?
    I ask because I have many threads getting and freeing memory and I've found that I get back null sometimes. This, I suspect, is the problem that's all the talk in the user forum with CS6 crashing with CUDA enabled. I'm starting to suspect that there is a memory management problem when there is also a lot of memory allocation and freeing going on by the CUDA driver. It seems that the faster the nVidia card the more likely it is to crash. That would suggest the CUDA driver (ie the code that manages the scheduling of the CUDA kernels) is in some way coupled to the memory use by Adobe or by Windows alloc|free too.
    I replaced the memory functions with _aligned_malloc|free and it seems far more reliable. Maybe it's because the OS malloc|free are thread safe or maybe it's because it's pulling from a different pool of memory (vs the Memory Suite's pool or the CUDA pool)
    comments?
    Edward

    Zac Lam wrote:
    The Memory Suite does pull from a specific memory pool that is set based on the user-specified Memory settings in the Preferences.  If you use standard OS calls, then you could end up allocating memory beyond the user-specified settings, whereas using the Memory Suite will help you stick to the Memory settings in the Preferences.
    When you get back NULL when allocating memory, are you hitting the upper boundaries of your memory usage?  Are you getting any error code returned from the function calls themselves?
    I am not hitting the upper memory bounds - I have several customers that have 10's of Gb free.
    There is no error return code from the ->NewPtr() call.
         PrMemoryPtr (*NewPtr)(csSDK_uint32 byteCount);
    A NULL pointer is how you detect a problem.
    Note that changing the size of the ->ReserveMemory() doesn't seem to make any difference as to whether you'll get a memory ptr or NULL back.
    btw my NewPtr size is either
         W x H x sizeof(PrPixelFormat_YUVA4444_32f)
         W x H x sizeof(PrPixelFormat_YUVA4444_8u)
    and happens concurrently on #cpu's threads (eg 16 to 32 instances at once is pretty common).
    The more processing power that the nVidia card has seems to make it fall over faster.
    eg I don't see it at all on a GTS 250 but do on a GTX 480, Quadro 4000 & 5000 and GTX 660
    I think there is a threading issue and an issue with the Memory Suite's pool and how it interacts with the CUDA memory pool. - note that CUDA sets RESERVED (aka locked) memory which can easily cause a fragmenting problem if you're not using the OS memory handler.

  • Can use the same thread safe variable in the different processes?

    Hello,
    Can  use the same thread safe variable in the different processes?  my application has a log file used to record some event, the log file will be accessed by the different process, is there any synchronous method to access the log file with CVI ?
    David

    Limiting concurrent access to shared resources can be better obtained by using locks: once created, the lock can be get by one requester at a time by calling CmtGetLock, the other being blocked in the same call until the lock is free. If you do not want to lock a process you can use CmtTryToGtLock instead.
    Don't forget to discard locks when you have finished using them or at program end.
    Alternatively you can PostDeferredCall a unique function (executed in the main thread) to write the log passing the apprpriate data to it.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • Native library NOT thread safe - how to use it via JNI?

    Hello,
    has anybody ever tried to use a native library from JNI, when the library is not thread safe?
    The library (Windows DLL) was up to now used in an MFC App and thus was only used by one user - that meant one thread - at a time.
    Now we would like to use the library like a "server": many Java clients connect the same time to the library via JNI. That would mean each client makes its calls to the library in its own thread. Because the library is not thread safe, this would cause problems.
    Now we discussed to load the library several times - separately for each client (for each thread).
    Is this possible at all? How can we do that?
    And do you think we can solve the problem in this way?
    Are there other ways to use the library, though it is not thread safe?
    Any ideas welcome.
    Thanks for any contributions to the discussion, Ina

    (1)
    has anybody ever tried to use a native library from
    JNI, when the library (Windows DLL) is not thread safe?
    Now we want many Java clients.
    That would mean each client makes its calls
    to the library in its own thread. Because the library
    is not thread safe, this would cause problems.Right. And therefore you have to encapsulate the DLL behind a properly synchronized interface class.
    Now the details of how you have to do that depends: (a) does the DLL contain state information other than TLS? (b) do you know which methods are not thread-safe?
    Depending on (a), (b) two extremes are both possible:
    One extreme would be to get an instance of the interface to the DLL from a factory method you'll have to write, where the factory method will block until it can give you "the DLL". Every client thread would obtain "the DLL", then use it, then release it. That would make the whole thing a "client-driven" "dedicated" server. If a client forgets to release the DLL, everybody else is going to be locked out. :-(
    The other extreme would be just to mirror the DLL methods, and mark the relevant ones as synchronized. That should be doable if (a) is false, and (b) is true.
    (2)
    Now we discussed to load the library several times -
    separately for each client (for each thread).
    Is this possible at all? How can we do that?
    And do you think we can solve the problem in this
    way?The DLL is going to be mapped into the process address space on first usage. More Java threads just means adding more references to the same DLL instance.
    That would not result in thread-safe behavior.

  • Is Persistence context thread safe?  nop

    In my code, i have a servlet , 2 stateless session beans:
    in the servlet, i use jndi to find a stateless bean (A) and invoke a method methodA in A:
    (Stateless bean A):
    @EJB
    StatelessBeanB beanB;
    methodA(obj) {
    beanB.save(obj);
    (Stateless bean B, where container inject a persistence context):
    @PersistenceContext private EntityManager em;
    save(obj) {
    em.persist(obj);
    it is said entity manager is not thread safe, so it should not be an instance variable. But in the code above, the variable "em" is an instance variable of stateless bean B, Does it make sense to put it there using pc annotation? is it then thread safe when it is injected (manager) by container?
    since i think B is a stateless session bean, so each request will share the instance variable of B class which is not a thread safe way.
    So , could you please give me any guide on this problem? make me clear.
    any is appreciated. thank you
    and what if i change stateless bean B to
    (Stateless bean B, where container inject a persistence context):
    @PersistenceUnit private EntityManagerFactory emf;
    save(obj) {
    em = emf.creatEntityManager()
    //begin tran
    em.persist(obj);
    // commit tran
    //close em
    the problem is i have several stateless beans like B, if each one has a emf injected, is there any problem ?

    Hi Jacky,
    An EntityManager object is not thread-safe. However, that's not a problem when accessing an EntityManager from EJB bean instance state. The EJB container guarantees that no more than one thread has access to a particular bean instance at any given time. In the case of stateless session beans, the container uses as many distinct bean instances as there are concurrent requests.
    Storing an EntityManager object in servlet instance state would be a problem, since in the servlet programming model any number of concurrent threads share the same servlet instance.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Web service client proxy thread safe?

    Is the jax-ws web service client proxy and port objects thread safe in Weblogic 10.3.4?
    Been searching through the docs but can't find any info on this.

    I have searched and it seems that with cxf it's safe to do something like this.
    Nobody knows if this is safe using metro?

  • Thread-safe design pattern for encapsulating Collections?

    Hi,
    This must be a common problem, but I just can't get my head around it.
    Bascially I'm reading in data from a process, and creating/updating data structuers from this data. I've got a whloe bunch of APTProperty objects (each with a name/value) stored in a sychronized HashMap encapsulated by a class called APTProperties. It has methods such as:
    addProperty(APTProperty) // puts to hashmap
    getProperty(String name) // retreives from hashmap
    I also want clients to be able to iterate through all the APTProperties, in a thread safe manner . ie. they aren't responsible for sychronizing on the Map before getting the iterator. (See Collections.synchronizedMap() API docs).
    Is there any way of doing this?
    Or should I just have a method called
    Iterator propertyIterator() which returns the corresponding iterator of the HashMap (but then I can't really make it thread safe).
    I'd rather not make the internal HashMap visible to calling clients, if possible, 'cause I don't want people tinkering with it, if you know what I mean.
    Hope this makes sense.
    Keith

    In that case, I think you need to provide your own locking mechanism.
    public class APTProperties {
    the add, get and remove methods call lock(), executes its own logic, then call unlock()
    //your locking mechanism
    private Thread owner; //dont need to be volatile due to synchronized access
    public synchronized void lock() {
    while(owner != null) {
    wait();
    th = Thread.currentThread();
    public synzhronized void unlock() {
    if(owner == currentThread()){
    owner = null;
    notifyAll();
    }else {
    throw new IllegalMonitorStateException("Thread: "+ Thread.currentThread() + "does not own the lock");
    Now you dont gain a lot from this code, since a client has to use it as
    objAPTProperties.lock();
    Iterator ite = objAPTProperties.propertyIterator();
    ... do whatever needed
    objAPTProperties.unlock();
    But if you know how the iterator will be used, you can make the client unaware of the locking mechanism. Lets say, your clients will always go upto the end thru the iterator. In that case, you can use a decorator iterator to handle the locking
    public class APTProperties {
    public Iterator getThreadSafePropertyIterator() {
    private class ThreadSafeIterator implements Iterator {
    private iterator itr;
    private boolean locked;
    private boolean doneIterating;
    public ThreadSafeIterator(Iterator itr){
    this.itr = itr;
    public boolean hasNext() {
    return doneIterating ? false : itr.hasNext();
    public Object next() {
    lockAsNecessary();
    Object obj = itr.next();
    unlockAsNecessary();
    return obj;
    public void remove() {
    lockAsNecessary();
    itr.remove();
    unlockAsNecessary();
    private void lockAsNecessary() {
    if(!locked) {
    lock();
    locked = true;
    private void unlcokAsNecessary() {
    if(!hasNext()) {
    unlock();
    doneIterating = true;
    }//APTProperties ends
    The code is right out of my head, so it may have some logic problem, but the basic idea should work.

  • Thread safe ?

    Hi
    This code is currently running on my companys server in a java class implementing the singleton pattern:
    public static ShoppingAssistant getInstance() {
        if (instance == null) {
            synchronized (ShoppingAssistant.class) {
                instance = new ShoppingAssistant();
        return instance;
    }1 Is there really a need for synchronizing the method?
    2 If you choose to synchronize it. Why not just synchronize the whole method?
    3 Is this method really thread safe? Is I see it a thread A could be preempted after checking the instance and seing that it is null. Thereafter another thread B could get to run, also see that instance is null and go on and create the instance. Thereafter B modifies some of the instance�s instance variables. After that B is preempted and A gets to run. A, thinking instance is null, goes on and create a new instance of the class and assigns it to instance, thus owerwriting the old instance and creating a faulty state.
    By altering the code like this I think that problem is solved although the code will probably run slower. Is that correct?
    public static ShoppingAssistant getInstance() {
        synchronized (ShoppingAssistant.class) {
            if (instance == null) {
                instance = new ShoppingAssistant();
    }Regards, Mattias

    public class Singleton {
    private static final instance = newSingleton();
    public static Singleton getInstance() {
    return instance;
    }This seems like it's so obviously the standard
    solution, why do
    people keep trying to give lazy solutions? Do they
    expect it to be
    more efficient that this?I can see one possible performance gains with a lazy solution:
    If you use something else in that class (besides getInstance()), but don't use getInstance, then you don't take the performance hit of instantiating the thing.
    Of course, this is dubious at best because how often do you have other static methods in your singleton class? And not use the instance? And have construction be so expensive that a single unnecessary one has a noticeably detrimental impact on your app's performance?

  • Thread-safe alternative to XmlValue

    Hi,
    I'm using bdb xml in an application which visualizes 3d data stored in xml. When I load the data, it will be written into the db and I#m using XPath as query language. This works quite good, but as I'm using multiple threads within my application, I can't use XmlValues for referencing into the database, because they are not thread-safe. But I need to store at least some of those references to get quick access to some data, or to run a new query, based on a result node from an earlier query, later from another thread. Those referenced nodes will change during runtime, so indices won't help. So what can I do or did I miss something?
    Thanks
    Bjoern

    Bjoern,
    You may have to explain a bit more, especially the part about "referenced nodes will change during runtime." XmlValue objects that reference nodes are only guaranteed valid until the either (1) the XmlResults object containing them has been deleted or (2) the transaction in which they were retrieved ends. There are exceptions but those are the general rules.
    The interfaces, XmlValue::getNodeHandle() and XmlContainer::getNode() exist to allow an application to store a string value that can be later resolved quickly back into an XmlValue. This works well unless the referenced node has been removed. It may be the answer you are looking for.
    Regards,
    George

  • Thread safe XSLT extension

    We have a servlet that gets called with a set of parameters. I want to set one of those parameters within my XSL extensions so that it is retrievable from the XSL code. Because the extensions are static and used by all XSL transforms, they are not thread safe. Static elements within the class are overwritten by whatever servlet thread last touched it. So my parameter may not be for the thread wanted, but some subsequent thread. How can I get around this without synchronization?

    Would you provide more details of how you define the extensions?

Maybe you are looking for

  • Best Practice - OSS IDs

    We are trying to implement a good process for requesting, checking out, and assigning the OSS ID's.  Can you please let us know what you do or perhaps best practice of this? Do you have SAP_ALL assigned to OSSUSER IDs? Do you require approval from a

  • NewDocumentMode Question

    I have two images that I am receiving from another program and I want to merge them into one image with each having 50% opacity.  I'm having trouble opening then in the proper way.  The file extension is "att" which boils down to a 16-bit grayscale,

  • Can SSMS Preserve Pascal Case?

    I used SMO to create a database, several tables, and several SPs.When I opened it in SSMS, every object name was in caps. I then used my keyboard to manually PascalCase them once again. Fine. But then I scripted the DB because it's supposed to be a p

  • Text selection tool is completely missing

    Hallo, I newly bought Adobe Acrobat XI. It's running on Windows 7. Unfortunately the text and graphic selection tool (the small arrow) is missing in the toolbar. It's not possible to select it to the toolbar - it doesn't appear anywhere. We installed

  • Can 2011 Mac Mini boot from Leopard and/or Snow Leopard?

    I want to replace my G5 with the latest Mini but need Rosetta to run my old PPC and Universal applications for a while longer.