Thread safe object cache

The case:
I have a case where I hold configuration about a web page in an xml-file. The configuration is cached in memory on first request then I retrieve the configuration from memory on every following request. If the configuration in the xml-file changes between requests I will release the current configuration from memory and renew it by reading from the file.
Since we are talking about http requests all this will happen in a heavy loaded multithreaded environment.
The current solution:
+public class ConfigFile {+
private static final ConfigCache REGISTRY;
+static {+
REGISTRY = ModuleRegistry.create();
+}+
+public static Element getConfigElement(final String configKey) {+
Element configElm = null;
+if(configFileIsChanged()) {+
REGISTRY.clear();
+}+
+if((configElm = REGISTRY.get(configKey)) == null) {+
+... //Reload configuration from xml-file+
REGISTRY.put(configKey, configElm);//and save to registry
+}+
return configElm;//Return config data as an xml-element
+}+
+... //Class impl..+
+//This inner class holds the configuration as dom element parts+
+private static class ConfigCache {+
+private HashMap<String, Element> _moduleRegistry;+
+public synchronized void put(final String key, final Element elm) {+
_moduleRegistry.put(key, elm);+
+}+
+public synchronized Element get(final String module) {+
+return _moduleRegistry.get(key);+
+}+
+public synchronized void clear() {+
_moduleRegistry.clear();+
+}+
+public static ConfigCache create(){+
return new ConfigCache();
+}+
+}+
+}+
Since the registry is declared as a class variable in the ConfigFile class I handle the put and get operations to it by synchronizing the access.
The problem/question:
Is if this is enough to handle possible threading issues when it comes to invalidating the registry. What happens if some thread tries to "get" from the registry when another just cleared it? I guess it needs to wait until it's reloaded, right?
Regards
Johannes

I wasn't clear enough in my previous post. Sorry for that.
The code will be executed in a servlet/JSP environment but it's not really relevant in this case except for the fact that there will be multiple threads accessing this code.
Think of it as an in memory data storage with information that will be read from the memory. The memory in this case is implemented as a static HashMap (the ConfigCache). I've wrapped it in the ConfigCache class since I want to synchronize the access to the put and get. All threads have access to the configuration file through the static method call ConfigFile.getModuleElement(somElementName);. This method is not synchronized.
Suppose we have 20 threads accessing this code concurrently. I'm not sure how the code will behave when this executes. My guess is that the critical parts are when one thread clears the HashMap, another tries to put something to the Map and another tries to get something.
I made an assertation test where I expected different results from 5 randomly executed web requests with 20 active threads reading and writing to the Map (the ConfigCache). It succeeds but I'm still not sure if I'm on the right track.
I've read a lot about this but I have not found any material describing this as clearly as I want it. In most cases they only explain how to use synchronized blocks and methods.
Are you with me or do you still think this belong in the servlet forum? Maybe it does?
BTW. How do I use code tags?

Similar Messages

  • Are CacheStore's and BackingMapListener's thread safe?

    I'm implementing a JMS CacheStore and have a quick question: does Coherence ever attempt to run multiple threads concurrently across a CacheStore instance on a given node?
    Reason I ask is that only certain objects are thread-safe in the JMS spec.: Connection Factories, Destinations (i.e. a Queue) and Connections. However Sessions, Producers and Consumers are not.
    In order to improve performance, it's recommended (obviously) to try and reuse Sessions/Producers and not recreate them for every message sent. So I'd like to declare them as instance variables in my class and assign them once-only at construction time.
    I just wanted to make sure that this would be OK (i.e. Coherence would start multiple threads running across my CacheStore). Anyone any ideas?
    (NB. I'm using JMS Connection Pooling to get around this issue at the moment - as the pools are thread-safe and I can close/open them quickly as many times as I like - but this is not a part of the JMS standard, so I end up using vendor-specific classes which I'd rather not do. Likewise I could make many of these non-thread-safe objects use ThreadLocals, but this all seems a bit overkill if it isn't actually required...)
    An other issue... :)
    What about closing the connection when it's finished with? Again, it's JMS recommended best-practice to do so. How is this best accomplished, seem as though it was Coherence that created the CacheStore instance and my client code has no reference to it? Best I can think of for now is have a static method in my CacheStore class that is kicked off via an invocation-service agent. Again, if anyone has a better idea I'm all ears.
    An other issue... :)
    Does the same thread-safety hit BackMapListeners? The "receiving" end of my JMS messages is a BackingMapListener based on the Incubator Commons "AbstractMultiplexingBackingMapListener" class. So, does Coherence ever kick off multiple threads across a single BackingMapListener instance, or can I safely have the JMS Session and Consumer left open after construction as class-level members?
    Cheers,
    Steve

    stevephe wrote:
    True... But I was rather hoping I could just get someone from Oracle who wrote the stuff to comment instead! :) Don't really want to second-guess this, as there could always be unusual corner-cases that could be difficult to replicate. Still...
    I did a bit more testing on my CacheStore this morning. I removed the non JMS-standard "pooling" and just created instance variables for only those items which I know to be thread-safe (ConnectionFactory, Connection and my target queue, a "Destination" in JMS terminology) I now re-get the Session and Producer in each Cachestore method. This makes the code thread-safe and portable. TBH, it hasn't affected performance too much, so I'll leave it as it is for now (and I've put a comment in the code stating that people could move these things to ThreadLocal's if they wanted to further boost performance in their own usage cases and still keep the CacheStore thread-safe.)
    As regards the "receiving" end of these published messages, my BackingMapListener does nothing more than register a JMS MessageListener and a "connection.start()" call. This is a very short, one-off call, so shouldn't leave Coherence service threads "hanging" on anything for extended periods.
    Cheers,
    SteveHi Steve,
    to cut things short:
    1. Coherence instantiates one cache store per read-write-backing-map, therefore it needs to be thread-safe if you have a thread-pool or use write-behind.
    2. If you don't have write-behind then Coherence uses the worker thread to execute the cache store operations.
    3. If you have write-behind then generally Coherence uses the write-behind thread (this is a separate thread per write-behind-configured service) to execute the cache store operations, except for erase[All]() operations on cache.remove() or batch remove which cannot be delayed due to consistency reasons and are executed on the worker thread.
    If you don't have a thread-pool, replace worker thread with service thread.
    I don't know off my head where the refresh-ahead operation executes.
    There is a single backing-map-listener per backing map instantiated, therefore it needs to be thread-safe. BackingMapManagerContext is thread-safe, so there is no issue with sharing it across multiple threads executing on a backing-map-listener.
    Best regards,
    Robert

  • [SOLVED] Singleton thread safe

    If I have a singleton object where all instance and class variables are thread safe objects, is that object thread safe?
    Edited by: 888903 on Oct 3, 2011 8:30 PM

    888903 wrote:
    If I have a singleton object where all instance and class variables are thread safe objects, is that object thread safe?First, "all instance and class variables are thread safe objects" cannot be true, because variables are not objects. Presumably you meant to say that these variables refer to threadsafe objects.
    As for your question, no, you cannot say that a given object is threadsafe just because all its member variables are. It depends on the semantics of your class, and what it needs to be atomic. For example, take the following class:
    public class Person {
      private String firstName;
      private String lastName;
      public String getName() {
        return firstName + " " + lastName;
      public void updateName(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }Here, we have a class like what you describe. (The fact your case involves a singleton is irrelevant.) My String member variables are threadsafe, but my Person class is not. If I start with "Joe Smith" and then later I call person.updateName("Fred", "Jones"), another thread could call getName() after I've updated the first but before the last, so he'd see "Fred Smith", which is incorrect. He should see only "John Smith" or "Fred Jones", not an intermediate value.

  • Swing thread safe ?

    Hi
    Are swing comonents are thread safe ?
    If i am not wrong the thread safe objects are those whose data changes are predictable ( i mean no race condition)
    Is this correct ?
    I had worked on multithreaded application in MFC where we used Message queues for hadling the multithreading
    Can i use the same logic in java also ? If yes can anybody help me how can i do it
    Thanks in advance

    The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html]Using Threads explains the concept of "Thread Safe".

  • 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.

  • HTTP request/response object not thread safe.

    According to the serlvet spec. Http Request/Response
    are not thread safe. Quoting from the Spec:
    " Implementations of the request and response objects are not guaranteed to be thread safe. This means that they should only be used within the scope of the request handling thread. References to the request and response objects must not be given to objects executing in other threads as the resulting behavior may be nondeterministic."
    This has prompt me to ask the following question.
    For Example I have a servlet which does the following
    request.setAttribute("myVar","Hello");
    The request and response is dispatched(using RequestDispatch.include(request,response)) to another
    servlet which retrieve this attribute i.e request.getAttribute("myVar");
    Is this safe?
    The Spec only said "The Container Provider must ensure that the dispatch of the request to a target
    servlet occurs in the same thread of the same VM as the original request." I take this meaning that the targeting servlet does not have to run in the same thread(only dispatch), otherwise it would be safe.

    To put it another way, you can only have onle thing working on a request at a time. For instance, the ServletContext is available to all servlets running on a server. If you tried to save a particular request to the ServletContext, it would potentially be available to many concurrently running servlets. They could all change whatever in it at the same time. Each servlet is in its own running thread. Hope that helps some.

  • Are static objects thread safe?

    hi,
    i have seen code that looks like this:
    private static TestObject _to;
    static {
    _to = new TestObject();
    if methods within TestObject contain local variables, will local variables inside _to be threadsafe when hit by 2 requests?
    eg.
    User 1 makes a request to:
    _to.setStuff("abc");
    User 2 make a request to:
    _to.setStuff("def");
    Will User 1's now see "def" instead of "abc"?
    thanks
    - Edward Han
    [email protected]

    so what happens to the local variable holder? if 2
    people access the static variable _to and call
    setStuff() one right after the other, is there a
    chance that the first person in will print out what
    the second person in set as the holder?
    Local variables are thread specific and live on an execution stack, and each thread gets its own stack. If there are two threads, there are two stacks, and if both threads are "in" setstuff(), there are two distinct references called "holder" -- one per stack. And regardless of the order in which the threads enter that method, the references themselves are not clobbered. Now, what you see printed is an entirely different issue, as is the case if the "holder" references point to the same (shared) object.
    The key is this: a thread-specific resource is thread safe; a shared (unprotected and/or mutable) resource is not.

  • Are immutable objects thread safe

    I am having a debate with legosa as to if immutable objects are thread safe @
    http://forum.java.sun.com/thread.jsp?forum=37&thread=525250
    I would like the java gurus to put in their thoughts over here.

    I am having a debate with legosa as to if immutable
    objects are thread safe @
    http://forum.java.sun.com/thread.jsp?forum=37&thread=52
    250
    I would like the java gurus to put in their thoughts
    over here.There are some problems with the java memory model that can cause immutable objects to not be thread safe. This is discussed in the section Problem#1 in the following article from IBM:
    http://www-106.ibm.com/developerworks/library/j-jtp02244.html
    According to this article, some of the problems have been fixed in jdk1.4, while other fixes will have to wait until jdk1.5.

  • Java.util.Locale not thread-safe !

    In multithreading programming, we know that double-checking idiom is broken. But lots of code, even in sun java core libraries, are written using this idiom, like the class "java.util.Locale".
    I have submitted this bug report just now,
    but I wanted to have your opinion about this.
    Don't you think a complete review of the source code of the core libraries is necessary ?
    java.util.Locale seems not to be thread safe, as I look at the source code.
    The static method getDefault() is not synchronized.
    The code is as follows:
    public static Locale getDefault() {
    // do not synchronize this method - see 4071298
    // it's OK if more than one default locale happens to be created
    if (defaultLocale == null) {
    // ... do something ...
    defaultLocale = new Locale(language, country, variant);
    return defaultLocale;
    This method seems to have been synchronized in the past, but the bug report 4071298 removed the "synchronized" modifier.
    The problem is that for multiprocessor machines, each processor having its own cache, the data in these caches are never synchronized with the main memory.
    The lack of a memory barrier, that is provided normally by the "synchronized" modifier, can make a thread read an incompletely initialized Locale instance referenced by the static private variable "defaultlocale".
    This problem is well explained in http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html and other documents about multithreading.
    I think this method must just be synchronized again.

    Shankar, I understand that this is something books and articles about multithreading don't talk much about, because for marketing reasons, multithreading is supposed to be very simple.
    It absolutely not the case.
    Multithreading IS a most difficult topic.
    First, you must be aware that each processor has its own high-speed cache memory, much faster than the main memory.
    This cache is made of a mixture of registers and L1/L2/L3 caches.
    Suppose we have a program with a shared variable "public static int a = 0;".
    On a multiprocessor system, suppose that a thread TA running on processor P1 assign a value to this variable "a=33;".
    The write is done to the cache of P1, but not in the main memory.
    Now, a second thread TB running on processor P2 reads this variable with "System.out.prinln(a);".
    The value of "a" is retrieved from main memory, and is 0 !
    The value 33 is in the cache of P1, not in main memory where its value is still 0, because the cache of P1 has not been flushed.
    When you are using BufferedOutputStream, you use the "flush()" method to flush the buffer, and the "synch()" method to commit data to disk.
    With memory, it is the same thing.
    The java "synchronized" keyword is not only a streetlight to regulate traffic, it is also a "memory barrier".
    The opening brace "{" of a synchronized block writes the data of the processor cache into the main memory.
    Then, the cache is emptied, so that stale values of other data don't remain here.
    Inside the "synchronized" block, the thread must thus retrieve fresh values from main memory.
    At the closing brace "}", data in the processor cache is written to main memory.
    The word "synchronized" has the same meaning as the "sync()" method of FileDescriptor class, which writes data physically to disk.
    You see, it is really a cache communication problem, and the synchronized blocks allows us to devise a kind of data transfer protocol between main memory and the multiple processor local caches.
    The hardware does not do this memory reconciliation for you. You must do it yourself using "synchronized" block.
    Besides, inside a synchronized block, the processor ( or compiler ) feels free to write data in any order it feels most appropriate.
    It can thus reorder assignments and instruction.
    It is like the elevator algorithm used when you store data into a hard disk.
    Writes are reordered so that they can be retrieved more efficiently by one sweep or the magnetic head.
    This reordering, as well as the arbitrary moment the processor decides to reconciliate parts of its cache to main memory ( if you don't use synchronized ) are the source of the problem.
    A thread TB on processor P2 can retrieve a non-null pointer, and retrieve this object from main memory, where it is not yet initialized.
    It has been initialized in the cache of P1 by TA, though, but TB doen't see it.
    To summarize, use "synchronized" every time you access to shared variables.
    There is no other way to be safe.
    You get the problem, now ?
    ( Note that this problem has strictly nothing to do with the atomicity issue, but most people tend to mix the two topics...
    Besides, as each access to a shared variable must be done inside a synchronized block, the issue of atomicity is not important at all.
    Why would you care about atomicity if you can get a stale value ?
    The only case where atomicity is important is when multiple threads access a single shared variable not in synchronized block. In this case, the variable must be declared volatile, which in theory synchronizes main and cache memory, and make even long and double atomic, but as it is broken in lots of implementation, ... )

  • Cache distribution - Java object cache

    Hi.
    I'm trying to use Oracle Java Object Cache (cache.jar), the one included in the 9iAS 9.0.3.
    Everything works fine but the cache distribution between different JVM:s.
    Anyone got this to work?
    Regards
    Jesper
    package test;
    import oracle.ias.cache.*;
    * Singleton Cache class.
    public class Cache {
         /** The singleton instance of the object. */
         private static Cache instance = null;
         /** The root region. */
         private final static String APP_NAME = "Test";
         * Protected constructor - Use <code>getInstance()</code>.
         * @throws Exception if error
         protected Cache() throws Exception {
              CacheAccess.defineRegion(APP_NAME);
         * Gets the singleton instance.
         * @return The instance of the Cache object.
         public static Cache getInstance() throws Exception {
              if (instance==null) {
                   createInstance();
              return instance;
         * Creates the singleton instance in a thread-safe manner.
         synchronized private static void createInstance() throws Exception {
              if (instance==null) {
                   instance = new Cache();
         * Put an object on the cache.
         * @param name The object name
         * @param subRegion The sub region
         * @param object The object to cache
         * @throws Exception if error
         public static void put(String name, String subRegion, Object object) throws Exception {
              CacheAccess appAcc = null;
              CacheAccess subAcc = null;
              try {
                   appAcc = CacheAccess.getAccess(APP_NAME);
                   // Create a group
                   Attributes a = new Attributes();
                   a.setFlags(Attributes.DISTRIBUTE);
                   appAcc.defineSubRegion(subRegion, a);
                   subAcc = appAcc.getSubRegion(subRegion);
                   if (!subAcc.isPresent(name)) {
                        subAcc.put(name, a, object);
                   } else {
                        subAcc.replace(name, object);
              } catch (CacheException ex){
                   // handle exception
                   System.out.println(ex.toString());
              } finally {
                   if (subAcc != null) {
                        subAcc.close();
                   if (appAcc != null) {
                        appAcc.close();
         * Gets a cached object from the specified sub region
         * @param name The object name
         * @param subRegion The sub region
         * @return The cached object
         * @throws Exception if requested object not in cache
         public static Object get(String name, String subRegion) throws Exception {
              CacheAccess appAcc = null;
              CacheAccess subAcc = null;
              Object result = null;
              try {
                   appAcc = CacheAccess.getAccess(APP_NAME);
                   subAcc = appAcc.getSubRegion(subRegion);
                   // define an object and set its attributes
                   result = (Object)subAcc.get(name);
              } catch (CacheException ex){
                   // handle exception
                   throw new Exception("Object '" + name + "' not in cache region '" + subAcc.getRegionName() + "'.");
              } finally {
                   if (subAcc != null) {
                        subAcc.close();
                   if (appAcc != null) {
                        appAcc.close();
              return result;
         * Invalidates all objects in all regions
         public static void invalidateAll() throws Exception {
              CacheAccess appAcc = CacheAccess.getAccess(APP_NAME);
              appAcc.invalidate(); // invalidate all objects
              appAcc.close(); // close the CacheAccess access
         // Main method for testing purposes.
         public static void main(String[] args) throws Exception {
              try {
                   System.out.println(">> Caching object OBJ1 into region TEST1.");
                   Cache.getInstance().put("OBJ1", "TEST1", "Object cached in TEST1.");
                   System.out.println(">> Getting OBJ1 from cache region TEST1.");
                   System.out.println(Cache.getInstance().get("OBJ1", "TEST1"));
              } catch (Exception ex) {
                   System.out.println(ex.getMessage());
    Contents of JAVACACHE.PROPERTIES:
    # discoveryAddress is a list of cache servers and ports
    discoveryAddress = host1.myserver.com:12345,host2.myserver.com:12345
    logFileName = c:\javacache.log
    logSeverity = DEBUG
    distribute = true

    I have same problem
    Exist some reason?
    I'm testing Cache with isDistributed() method and I still got false!
    Thanx

  • Thread Safe Testing

    I havn't written much mult-threaded code but I realise it's important when many web round-trips are required.
    How do I design, test and verify that I have a thread-safe application? I don't like relying on the testing statistics of chance unless the odds of failure are 0.0001%!
    Is there a correct way to verify a thread-safe application?

    I agree it is a lofty, though sadly in all probability too time consuming, goal to achieve. However, there are a few pitfalls to watch out for that should get most of the common, pernicious thread safety issues:
    Synchronize data that must be shared. This will involved performance bottle-necks. If the data is read-mostly, consider a Singleton cache. Though pitfalls will always remain here. Data sharing among threads, IMO, is the single greatest issue.
    Use static methods and instances wisely. If an object has instance variables that are used from method to method call (either within the class or from the caller), then state exists for that object. It is inherently a candidate to look at in terms of thead-safety. This class should be created for each logical unit of work that depends on its state. So, do not reuse these classes among threads (or at least provide an init() or reset() method to clear the state). The same applies to static methods. You can safely use a static method from multiple threads if it does not modify other static variables (e.g., changing the state of a static variable).
    Within the Collections API, pay attention to which types are synchronized and which are not. The Javadocs will specify.
    Try to write methods thread-safe. Have them only use the arguments provided in the method's signature.
    Watch for relatively simple race conditions that can easily be spotted.
    static private Singleton INSTANCE;
    private Singleton() {
        super();
        // Now I will fetch values from a database, perhaps taking seconds
    static final public Singleton getInstance() {
          if (INSTANCE == null) {
             INSTANCE = new Singleton();  // what if this takes some time, e.g. database query to get cache values?
          return INSTANCE;
    }Not good. Here's a possible refactoring:
    private static final Singleton INSTANCE;  // bonus, we can now make it final
    static {
       INSTANCE = new SIngleton();  // Occurs only when class is loaded, atomic
    public static final Singleton getInstance() {
      return INSTANCE;  // no race condition
    }The above would be even more applicable and pronounced if you offered a static refresh() method on the instance, say to refresh its cache of data from a database.
    Seems easy, right? The rub is that you need to verify that a given method does not call other methods that are not thread-safe. If every class you design follows the above precepts, then you will probably only be chasing down rarer thread-safety issues.
    - Saish

  • 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

  • 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.

Maybe you are looking for