Is this thread safe?

I've got a HttpServletRequest instance variable in my servlet that I use in my model to retrieve parameters. The servlet looks like:
public class MyServlet extends HttpServlet implements Controller {
  HttpServletRequest req;
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    processRequest(req, resp);
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    processRequest(req, resp);
  public void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    this.req = req;
    MyModel model = new MyModel(this);
    model.retrieve();
  public String getParameter(String parameter) {
    return req.getParameter(parameter);
}The Controller interface has only one method - public String getParameter(String parameter)
In MyModel because I pass an instance of Controller into the constructor I can do - controller.getParameter(parameter);
Is what I'm doing thread safe?

Actually, a static nested class is more appropriate than an inner class as there is no implicit outer-class reference to maintain:
public class MyServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        processRequest(req, resp);
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        processRequest(req, resp);
    public void processRequest(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        MyModel model = new MyModel(new MyController(req));
        model.retrieve();
    private static class MyController implements Controller {
        private HttpServletRequest req;
        MyController(HttpServletRequest req) {
            this.req = req;
        public String getParameter(String parameter) {
            return req.getParameter(parameter);
}This code is now thread safe because there is a different instance of MyController per thread. Note that if an instance of MyController is accessed by multiple threads, then its thread safety is dependent upon the thread safety of HttpServletRequest. However, based on the sort of thing I assume you are trying to do, I doubt you will be sharing instances between threads.

Similar Messages

  • Thread safe - again

    Hi guys,
    If I have 2 threads
    Thread one = new Thread();
    Thread two = new Thread();
    In each Thread (one, two) in run method, I new a class called MyClass
    public class myClass
    public int a;
    public int b;
    public int geta()
    return a;
    public int getb()
    return b;
    public void seta(int x)
    this.a = x;
    public void setb(int y)
    this.b = y;
    Is this thread safe. My result is not a thread safe. Does these 2 thread access the same memory block of myclass? I am really confused now.
    Thanks

    I agreed with the previous reply that the two myClasses shouldn't share the memory. But there are still many factors which may let them actually share the memory, such as you are actually implementing the two threads by putting the two myClasses into same variable (like static). Anyway, I think it is better for you to post how you create and store those classes in here. Then a clear reason and solution will come out.

  • Non-thread safe System.console(), although synchronized used?

    Hi, I recently noticed that the System.console() code looks like the following:
    public static Console console() {
             if (cons == null) {
                 synchronized (System.class) {
                     cons = sun.misc.SharedSecrets.getJavaIOAccess().console();
             return cons;
         }Is this thread safe, despite the synchronized block? I mean, suppose two threads try to get the console, and they both go past the null check. Then, one of them gets the lock, initializes the field blah blah. Then, the second gets the chance to run, and since it is past the null check, it will enter the synchronized code again. I don't know what happens in the sun.misc package, but as far as this code is concerned, this doesn't look valid to me. I might be wrong though :-)
    Cheers.

    DeltaGeek wrote:
    Correct, that is not thread-safe. Why not just make the entire method synchronized?Because if cons is already non-null, there's no need to synchronize (assuming cons is the same object for each thread, something not evident in the code snippet...)
    I'd put forth this:
    public static Console console() {
             if ( null == cons ) {
                 synchronized (System.class) {
                     // need second check in case cons was set while the thread
                     // was blocked
                     if ( null == cons ) {
                         cons = sun.misc.SharedSecrets.getJavaIOAccess().console();
             return cons;
         }And yes, I always put the non-L-value first, just in case I make a typo like this:
    int x;
    if ( x |= SOME_CONSTANT ) ...

  • Making set iterator thread-safe?

    Please consider:
    Set set = new HashSet();
    ........... // put stuff in "set"
    for(Iterator it = set.iterator(); it.hasNext(); ) {
      // <------ danger?
      Object s = (Object) it.next();
    }The only way to make this thread-safe??:
    Set set = new HashSet();
    synchronized(set) {
      for(Iterator it = set.iterator(); it.hasNext(); ) {
        Object s = (Object) it.next();
    }A different thread could, in theory, empty "set" between "it.hasNext()" and "it.next()"?
    So the entire (possibly huge/time consuming) "for" loop must be completely synchronized?
    thanks.

    rdkh wrote:
    DrClap wrote:
    Yes, that's correct. If you don't want anything else to monkey with the set while you're iterating over it, then obviously you have to lock everybody else out.what i was trying to explore was the one line of byte code between:
    (line A) it.hasNext()
    // <------- chance of the jvm swapping in a different thread and running its code that references to "set", and performs add/remove on "set" that effects the iterator
    (line B) it.next
    That chance has just got to be near 0. I mean, the lines are right next to each other in the same thread.It can happen so you have to assume it will. Thread safety is not about playing the odds. When the scheduler decides to switch a thread out, it does so. No matter what, it will be between to steps that are right next to each other. The fact that they're also "logically" close is 100% irrelevant.
    And of course, if it's a multicore or multi-CPU machine, you can get other threads coming in between those statements without this thread even being swapped out.
    And synchronizing might in theory hurt performanceBeing fast won't matter if you can't be sure it's right.
    Edited by: jverd on Jan 19, 2010 11:43 AM

  • How to make thread safe?

    Hi guys,
    I got a backing bean like
    public class UserBean{
    private String firstname;
         public String getFirstname() {
              return firstname;
         public void setFirstname(String firstname) {
              this.firstname = firstname;
    the firstname variable is also use in the jsp page like
    <h:outputText value="#{userBean.firstname}"/>
    If the "setFirstname" method is executed by two threads, then it's likely that the value of the firstnameinstance variable will be replaced by the second thread while the first thread is still using it. So does JSF handle this thread safe condition? Please advice, Thanks !
    regards,
    kmthien

    If the bean is scoped in the request, according to the servlet spec, only one thread should ever access it. If the bean in scoped in the session/application, then it's up to you to manage synchronization within your bean as with every other web framework.

  • Unmodifiable Map of Immutable Entries / Is it thread safe?

    Hey, is a Map like this thread safe?
            Map<Currency, BigDecimal> map = new HashMap<Currency, BigDecimal>();
            map.put(Currency.getInstance("USD"), new BigDecimal("1.1"));
            map.put(Currency.getInstance("TWD"), new BigDecimal("1.2"));
            map.put(Currency.getInstance("EUR"), new BigDecimal("2.1"));
            map = Collections.unmodifiableMap(map);If so, will it perform better than synchronizedMap / ConcurrentHashMap?

    Often the point of using multiple threads is to improve performance, but if you use slower strutures you are throwing away that advantage.
    To illustrate, I have created a class which hold the same dynamic structure, but create much less objects.
    The example you have given I called lotsOfObjects and a more light weight version I called liteMap. The output of the test running on an old laptop is as follows.
    COLD liteMap     : Average call time 692 ns
    COLD lotOfObjects: Average call time 2,287 ns
    WARM liteMap     : Average call time 77 ns
    WARM lotOfObjects: Average call time 982 ns
    WARM liteMap     : Average call time 80 ns
    WARM lotOfObjects: Average call time 972 ns
    WARM liteMap     : Average call time 63 ns
    WARM lotOfObjects: Average call time 1,068 nsThe point I would like to make is that for this micro-benchmark, you would need to scale your application efficiently across a dozen cores in the slower case, just to given you the throughput of faster case running on one core.
    The test code.
    import java.math.BigDecimal;
    import java.util.Collections;
    import java.util.Currency;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.concurrent.Callable;
    import static EnumDoubleMapTest.CurrencyEnum.*;
    public class EnumDoubleMapTest {
        enum CurrencyEnum {
            USD, EUR, TWD
        public static void main(String... args) throws Exception {
            Callable<Map<java.util.Currency, BigDecimal>> lotOfObjects = new Callable<Map<java.util.Currency, BigDecimal>>() {
                public Map<java.util.Currency, BigDecimal> call() throws Exception {
                    Map<Currency, BigDecimal> map = new HashMap<Currency, BigDecimal>();
                    map.put(Currency.getInstance("USD"), new BigDecimal("1.1"));
                    map.put(Currency.getInstance("TWD"), new BigDecimal("1.2"));
                    map.put(Currency.getInstance("EUR"), new BigDecimal("2.1"));
                    return Collections.unmodifiableMap(map);
            Callable<EnumDoubleMap<CurrencyEnum>> liteMap = new Callable<EnumDoubleMap<CurrencyEnum>>() {
                public EnumDoubleMap<CurrencyEnum> call() throws Exception {
                    return new EnumDoubleMap<CurrencyEnum>(CurrencyEnum.class)
                            .put(USD, 1.1)
                            .put(TWD, 1.2)
                            .put(EUR, 2.1)
                            .seal(); // makes read only without creating another object.
            for (int i = 0; i < 4; i++) {
                timeTest("liteMap", liteMap, i > 0);
                timeTest("lotOfObjects", lotOfObjects, i > 0);
        private static void timeTest(String desc, Callable callable, boolean warm) throws Exception {
            long start = System.nanoTime();
            int runs = 10 * 1000;
            for (int i = 0; i < runs; i++) {
                callable.call();
            long time = System.nanoTime() - start;
            System.out.printf("%s %-12s: Average call time %,d ns%n", warm ? "WARM" : "COLD", desc, time / runs);
    import sun.misc.SharedSecrets;
    public class EnumDoubleMap<T extends Enum<T>> {
        private final Class<T> enumType;
        private final T[] enumKey;
        private final double[] values;
        private boolean sealed = false;
        EnumDoubleMap(Class<T> enumType) {
            this.enumType = enumType;
            enumKey = getAllValues(enumType);
            values = new double[enumKey.length];
        public static <T extends Enum<T>> EnumDoubleMap<T> of(Class<T> enumType) {
            return new EnumDoubleMap<T>(enumType);
        public double get(T t) {
            return values[t.ordinal()];
        public EnumDoubleMap<T> put(T t, double d) {
            assert !sealed;
            values[t.ordinal()] = d;
            return this;
        /*  Many more methods */
        public EnumDoubleMap<T> seal() {
            sealed = true;
            return this;
        private static <T extends Enum> T[] getAllValues(Class<T> enumType) {
            try {
                return (T[]) SharedSecrets.getJavaLangAccess().getEnumConstantsShared(enumType);
            } catch (Throwable t) {
                try {
                    return (T[]) enumType.getMethod("values").invoke(enumType);
                } catch (Exception e) {
                    throw new AssertionError(e);
    }

  • Is this method thread safe?

    Hi Guys
    I have the following code:
    public class MyClass extends HttpServlet {
         HttpSession session;
         public doGet(HttpServletRequest request, HttpServletResponse response)
                                      throws IOException, ServletException                              
              session = request.getSession(false);
              List<AClass> htransactions = (List<AClass>)session.getAttribute("AClass");
                   //do stuff here
    }What I want to know is that if the HttpSession session is declared as a instance variable, does this make it non thread safe? Or is using such a way of for a session fine?
    .

    Steve declared a thumb-rule.
    Bear Bibeault
    sheriff & author
    Member # 24697
    posted Yesterday 9:17 PM
    Yes, variables created inside methods are safe because each thread will get their own copies. Instance variables are unsafe because they are shared across all threads.
    Keep this in memory, hope this was a perfect clarification...you can declare now on the answer.

  • Is this code thread safe?

    I've been seeing some information that makes me think that some servlet code I have that I thought was thread-safe actually isn't. I have a servlet that takes a POST request and calls a stored procedure on a database to do some inserts.
    public void doPost(HttpServletRequest request, HttpServletResponse response)
      // Check validity of request then proceed.
      if (valid) { postPayment(request); }
    synchronized private void postPayment(HttpServletRequest request)
      /* Take some parameters from the request and call the stored procedure */
    }What I'm attempting to do is ensure that 2 requests with the same data don't attempt to insert to the database at the same time. Have I accomplished that or do I need a different approach?

    Meatwad wrote:
    What if I had a static synchronized java bean that a member variable of the servlet class?As stated in my previous post:
    even that wouldn't be enough if there's more than one server running your app.and
    Since it database operations that you want to make atomic, the right place to ensure that is in the database.and
    The database is the only place where you're guaranteed a shared point of access to the resources you're trying to protect, so that's the appropriate (only) place to provide that protection.For an academic exercise with a single server, and if no other servlet or app is modifying the relevant tables, your approach is probably sufficient. But when all is said and done, a database transaction is the appropriate way to ensure exclusivity and atomicity of database operations.
    EDIT: Now, when you say "java bean", if you in fact are referring to an EJB, then I think they have their own tools and idioms for exclusivity and atomicity that encompass Java level syncing and DB transactions. I'm don't know anything about that though.
    Edited by: jverd on Jun 22, 2011 10:23 AM

  • Is this statement thread safe?

    Please tell whether the following statement is thread safe.
    counter++;
    (whether it is necessary to place it inside synchronized??)
    thanks,
    hawkins

    I believe the operation you describe is atomic so is "synchronized" if you prefer.
    That doesn't mean that your method will be thread-safe, though. An individual operation does no damage on its own - it's only when something else happens that thread-safety becomes an issue.
    If your question is "will my counter increase by 2 if two threads call counter++ at the same time?" then the answer is "yes".
    Thread-safety concerns the order in which operations happen across multiple threads, not whether they happen.
    If you're still not sure then please post up some context about what you're trying to do and perhaps some code to indicate where you think there may be a risk with concurrent access.

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

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for