Locking a non-thread-safe DLL, innovative solutions?
Hi,
I need to be able to lock access to a non-thread-safe third party DLL, so that multiple threads cannot access DLL simultaneously. I know that I can use semaphore or a single element queue. Are there any other innovative solutions that would limit the access to the DLL to a single call simultaneously.
If I use either semaphores or single element queue and use the semaphore (queue) with the same name in multiple programs (independent VIs), will the access to the DLL be handled without problems i.e. no collisions can happen? What if I build multiple applications (.exe) or application libraries (.dll), does a single semaphore (queue) still work between different applications or do they need to be initiated from the same application?
Tomi
Message Edited by Tomi M on 03-06-2006 08:01 PM
Tomi Maila
Tomi M wrote:
One more thing, with
innovative solutions I meant something like the following. Is there a
way to use some properties of Labview execution system to automatically
restrict the access to the DLL i.e. allow only single thread with
certain properties to call the DLL while all other threads with the
same properties are waiting in the execution queue. So if I set the
execution priority to something specific and execution system to
another something specific, will Labview thisway restrict access to DLL
to be sequential?
The proper way to
call non multithread safe DLLs in LabVIEW is to configure the Call
Library Node in the configuration dialog to be NOT reentrant. This
tells LabVIEW that the DLL may behave badly or at least you do not want
LabVIEW to call the DLL just from any thread. LabVIEW then will call
this DLL function from the UI execution system which is guaranteed to
only have one single thread at all times and therefore protect your DLL
from being called frm different threads at the same time.
Rlf Kalbermatter
Rolf Kalbermatter
CIT Engineering Netherlands
a division of Test & Measurement Solutions
Similar Messages
-
<snip>
This (as you probably know) is due to the fact that the code provided by
most of the DB vendors is not thread safe.
<snip>
Sean's comment, above, speaks to an issue that is causing some concern
within my (large - 180 projects in development) organisation.
May I please ask the forum if there are others out there who have an
understanding of / concern with this "problem"?
My perception (quite possibly flawed) of the "problem" is that the RDBMS
cannot multi-thread data access objects. So we find ourselves in a situation
where we can achieve scaleability in just about all other
performance-sensitive areas of a system's technical architecture (we're
using DCE -- but have found that Encina is not advisable except where there
is a true requirement for heterogeneous distributed 2 phase commit, which we
don't often see.....) but when we go to hit on the RDBMS, we go back to good
ole single-threading.
In certain circumstances, this shortfall of RDBMS technology -- I won't
mention any names, of course, but the initials are "Oracle" -- seems to be
hindering our achievement of a desired technical architecture.
Is this a "Pro*C / PL/SQL stored procedures" problem or is it something that
is in the RDBMSs' DNA?
How can we get around it?
Any comments?
Regards
JonJon
I agree. But it is the best solution within the constraints of existing
technology. At least we don't use a process per client. 10 replicated
copies of a service could service the needs of 100 clients.
Eric
>
At 13:15 6/09/96 EST, you wrote:
Eric
Thanks for your response. Yep. I realise that the issue I've presented is
clearly not something that Forte causes or is responsible for in any way.
Forte can, as you've pointed out, actually help in this area. But I don't
think that getting Forte to spawn another instance of a data access server
is really the best solution. Ie, that's not what we tend to have in mind
when we think about "scaleability". The best solution is -- perhaps -- to
get the RDBMS people to thread-safe all code and libraries. I have pointedly
asked Oracle for a position on this -- and got the usual blank stare.
I also considered whether people might get upset at me for posting what is
clearly a non-Forte-specifc question in a Forte forum. But then I went ahead
and did it anyway. Justification being (assumption follows) that the kind of
people who hang out on the Forte forum may tend to be more
architecture-oriented than your run of the mill VB / SQL*Net / PL/SQL stored
procedures kinda guy/gal, and may be using or considering Forte (plug for
Forte follows) precisely because it clearly enables a superior architecture.
Should proably post to the comp.database.oracle forum, but I just don't know
them as well.
Regards
Jon
From: Eric Gold
To: McLeod, Jon
Cc: [email protected]
Subject: Re: RDBMS non-thread-safe issue
Date: Friday, 6 September 1996 11:21AM
Jon
In response to this message.....read below...
Sean's comment, above, speaks to an issue that is causing some concern
within my (large - 180 projects in development) organisation.
May I please ask the forum if there are others out there who have an
understanding of / concern with this "problem"?
My perception (quite possibly flawed) of the "problem" is that the RDBMS
cannot multi-thread data access objects. So we find ourselves in a situation
where we can achieve scaleability in just about all other
performance-sensitive areas of a system's technical architecture (we're
using DCE -- but have found that Encina is not advisable except where there
is a true requirement for heterogeneous distributed 2 phase commit, which we
don't often see.....) but when we go to hit on the RDBMS, we go back to good
ole single-threading.
In certain circumstances, this shortfall of RDBMS technology -- I won't
mention any names, of course, but the initials are "Oracle" -- seems to be
hindering our achievement of a desired technical architecture.
Is this a "Pro*C / PL/SQL stored procedures" problem or is it something that
is in the RDBMSs' DNA?
How can we get around it?
Any comments?Jon,
Go ahead ask the Forum any questions you want. This "problem"
is not a problem in Forte. What we allow you to do is "replicate" your
data access services so that each one runs inside its own
process. Each one of these processes (aka partitions) has its
own connection to the database. The routing to the replicated
partitions is transparent to the clients. Clients send a
message like "DatabaseService.GetCustomer()" and then the Forte
router sees which replicated copy of the service is not currently
processing a request and routes it to that free replicate. You
can dynamically increase or decrease the number of replicated
copies of the service easily.
We call this feature "load balancing" in Forte. It is achieved
by checking a box in the data access service object definition.
You can dynamically increase/decrease the number of replicates
and also dynamically move replicates to other nodes in the environment.
This approach assumes that you are using application driven
security and not database security. Each replicated copy
of the service is using the same generic username/password
to connect to the database.
I am forwarding this answer to forte-users because others
might not completely understand this feature.
Eric
Eric Gold
Technical Director
Forte Australia
Voice: 61-2-9926-1403
Fax: 61-2-9926-1401
Eric Gold
Technical Director
Forte Australia
Voice: 61-2-9926-1403
Fax: 61-2-9926-1401 -
List of Non-thread safe system calls in Solaris 2.6??
Hi,
I'm searching for a list of system calls which are known to be non thread safe in a multithreaded process in Solaris 2.6. Anyone know of such a list?I'm not aware of any list but you can easily find the list by looking for the following pattern in the man pages :-)
| ATTRIBUTE TYPE| ATTRIBUTE VALUE|
|__________________________________
| MT-Level | Unsafe |
|_______________|_________________|
HTH
Angelo
Sun Developer Support. -
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 ) ... -
Thread-safe dlls: re-entrant
Hi!
I've been trying to research on multi-threaded dlls w/ jni, & it seems every native method HAS TO BE synchronized. Unfortunately, my reqs call for native methods that are NOT ENTIRELY synchronized. The option I came across was TLS, although actually I was looking for better options. Then I found Roedy Green's advice that TLS was not even an option!
Help! It seems that if native methods are NOT synchronized, any variable will be prone to being overwritten when multiple java objects call the method? My assumption is that native code is not translated into unique object space for each object since a dll is involved.
TIA,
ReggieThanks again for your patience! Let me restate my
problem: I need several instances of the same class
running the same JNI code, w/c of course reside in a
dll. I want my classes to be thread-safe, so I thought
of using Thread-Local-Storage. Unfortunately, I found
references on the web that JNI does not work w/ TLS.
Neither can I simply "synchronized" the whole native
method from java. Do I have other options?
I still must not be precise enough.
For java and C++ there are two types of variables (created various ways): single thread visible and multi-thread visible. For example:
- Java/C++ static class variable (multi-thread visible)
- Java/C++ member class variable (single thread visible)
- Java/C++ local (method) variable (single thread visible)
There are three interfaces to the variables:
-Java only.
-C++ only.
-Java variables accessed in a JNI method.
So there are six possible cases.
1. Java only, single thread visible. Absolutely nothing you do will make these visible to other threads so there is never any point to synchronization
2. C++ only, single thread visible. Again you can't see these in other threads so it doesn't matter.
3. Java only, multi-thread visible. You have to synchronize these variables using java methods.
4. C++ only, multi-thread visible. You have to synchronize these variable using C++ methods. Keep in mind that if you got to this point using java then you are still in a C++ thread - the jvm created it. The only problematic aspect is if the OS supports multiple thread models (Windows doesn't.) Then you have to determine the model to use the correct locking mechanism.
5. JNI, single thread visible. Again you can't see these in other threads so it doesn't matter.
6. JNI, multi-thread visible. In this case you need to create a java synchronization method in your C++ code. For example if you want to access a static variable of a java class in C++ you would have to synchronize it. In this case I would strongly recommend writing a java method and calling that instead. The synchronization code will be much easier to understand in java and it will significantly simplify the C++ code.
Now the above cases should cover everything. If not you need to specifically tell me what is missing. -
Discussion: AtomicBuffer - lock-free and thread-safe
Hi,
Since I'm always interested in discussions, I posted the following code for a lock-free, thread-safe buffer implementation.
In this case the buffer stores (Message,Throwable, Level) triplets but that's not the point here.
The interesting parts are addEntry() and getNextSlot(). It's actually the first time, that I tried to make use of the atomic package in a real application.
I'm looking forward to any kind of valuable comment, may it be criticism or praise :)
Cheers, Daniel
* Array-based buffer for storing message-throwable-level triples.
* Uses CAS for lock-free, thread-safe access.
* @author dgloeckner
public class AtomicBuffer {
private final int mSize;
private Object[] mMessageBuffer;
private Throwable[] mThrowableBuffer;
private Level[] mLevels;
private AtomicInteger mNextSlot;
private AtomicInteger mDiscardedMessages;
public AtomicBuffer(int pSize) {
super();
mSize = pSize;
mMessageBuffer = new Object[pSize];
mThrowableBuffer = new Throwable[pSize];
mLevels = new Level[pSize];
mNextSlot = new AtomicInteger(0);
mDiscardedMessages = new AtomicInteger(0);
* Uses CAS for lock-free, thread-safe buffer access.
* @param pMessage log message
* @param pThrowable throwable for the message (may be null)
* @param pLevel log level
public void addEntry(Object pMessage, Throwable pThrowable, Level pLevel) {
int lSlot = getNextSlot();
if (lSlot < mSize) {
mMessageBuffer[lSlot] = pMessage;
mLevels[lSlot] = pLevel;
mThrowableBuffer[lSlot] = pThrowable;
} else {
//Buffer is full
mDiscardedMessages.incrementAndGet();
* Returns the next free slot.
* Only increments the next slot counter,
* if free space is left.
* @return next free slot
protected int getNextSlot() {
int lNextSlot = 0;
//CAS loop checks if the value read from mNextSlot
//is smaller than the buffer size.
//If not, the loop returns.
//If yes, the loop tries to increment mNextSlot using CAS.
do {
lNextSlot = mNextSlot.get();
if (lNextSlot >= mSize) {
break;
} while (!mNextSlot.compareAndSet(lNextSlot, lNextSlot + 1));
return lNextSlot;
public int getSize() {
return mSize;
public int getDiscardedMessages() {
return mDiscardedMessages.get();
public Level[] getLevels() {
return mLevels;
public Object[] getMessages() {
return mMessageBuffer;
public Throwable[] getThrowables() {
return mThrowableBuffer;
* Returns the number of filled slots.
* @return number of filled slots
public int getFilledSlots() {
return mNextSlot.get();
}Hi,
OK, so we were talking about different specifications.
If you are sure about that before the time you mentioned only writes, and after that time only read(s) will take place, it's an absolutely good situation.
Sorry, I was very wrong, you're right - some (or most) implementations use hardware CAS. Hey that's a nice feature, isn't it?
I can see that you are using the loop to determine, whether another thread has accessed the counter (or something similar). I think this technique is great,
however, you might end up with a thread waiting for a single buffer space, while the others proceed (although this is not likely).
Anyway, I don't really know why would I want to use a code this complicated.
What about these lines:
public void addEntry(Object pMessage, Throwable pThrowable, Level pLevel) {
int lSlot = mNextSlot.incrementAndGet();
//So this has incremented the value (now remember to instantiate with -1) atomically, fast, with no locking and no loops
//Here I don't really worry about the real value of this int, as I only want to know if my entry fits to the buffer
if (lSlot < mSize) {
mMessageBuffer[lSlot] = pMessage;
mLevels[lSlot] = pLevel;
mThrowableBuffer[lSlot] = pThrowable;
public int getDiscardedMessages(){
return mNextSlot.get()-mSize; //but here I can reuse the information (i.e. the difference), which you would have discarded
}To use this code for general purposes, one could modify it like this:
<code>...
//in the constructor:
fillableSize = pSize;
mSize = pSize + OVERFLOW; //where OVERFLOW is a number that satisfies the conditions in a given environment
</code>...
public boolean isFull(){
return mNextSlot.get() > fillableSize;
//I am sure that there is a thread periodically checking / storing the log itself, of which core should be something like this:
if (currentAtomicBuffer.isFull()){ //or a given time period is exceeded
AtomicBuffer newAtomicBuffer = new AtomicBuffer(BUFFER_SIZE);
logThisToDatabase(lastAtomicBuffer); // log the previous one - there should not be any writer threads
lastAtomicBuffer = currentAtomicBuffer; // this is the preivous one - note that there might be some threads writing to it, but this does not mean any problem
currentAtomicBuffer = newAtomicBuffer; // from now on, work to the new buffer
//for monitoring purposes, you still can use getDiscardedMessages: this will inform you if OVERFLOW is set right. Anyway, it should always return 0.However, one might want to catch the interruptedException (thrown in the thread that empties the buffer) and handle it with a last logThisToDatabase call on lastAtomicBuffer and currentAtomicBuffer as well.
Kind Regards,
Zoltan -
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,
Stevestevephe 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 -
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. -
Thread Safe Queue Between DLL and EXE
Hello,
We wondered if this architecture would work:
An exe would create a thread safe queue. A dll routine would write to the queue using CmtWriteTSQData. The exe in turn would have an installed callback for the queue for when there are a certain number of items in the queue.
The exe is linked to DLL.
Thank you,
Solved!
Go to Solution.Hi jharris66,
It sounds like that architecture you suggest should work. However I am not sure what you mean when you say the exe is linked to the DLL. Could you clarify what you mean when you say that?
Thank you!
Rachel M.
Applications Engineer
National Instruments -
If can think the thread safe variable as another lock method
Hello,
Assuming that there are two threads, using a thread safe variable as a signal condition. When the 1st thread calling the GetPointerToVarName() to do something, at the "same time", the 2nd thread need to call GetPointerToVarName() to modify something, I'd like to know if the 2nd thread can continue the work until the 1st thread call the ReleasePointerToVarName()?
DavidThread safe variables can only be accessed by one thread at a time, so while the first one is holding the pointer, the second one waits until the pointer is released.
This is more rigid than using thread locks, in that a thread could call CmtTryToGetLock remaining free to run even if the lock cannot be acquired (supposing running without the locked object makes sense).
But it is not clear to me from your question whether you actually want thread safe variable functions to lock or are afraid they will do so...
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? -
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 -
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. -
ODBC SQLGetData not thread-safe when retrieving lob
Hi MaxDB developpers,
we are in the process of migrating our solution from SapDb 7.4.03.32 to MaxDb 7.6.03.7. We use the ODBC driver on windows, from multi-threaded applications.
We encountered bugs in the ODBC driver 7.4.03.32 and made our own fixes since we had the sources. I checked if these problems were fixed in 7.6.03.7 and they are allmost addressed, but one:
when two threads use two different stmt from the same dbc and call simultaneously SQLGetData to retrieve a LONG column, a global variable not protected by a critical section is changed and the application crashes. The variable in cause is dbc_block_ptr->esqblk.sqlca.sqlrap->rasqlldp which is set by pa30bpcruntime and reset by pa30apcruntime during the call to apegetl. Calls to apegetl are protected by PA09ENTERASYNCFUNCTION except in SQLGetData, when it calls pa60MoveLongPos or pa60MoveLong.
Since MaxDB is a critical feature of our application, we would like to know when this bug can be fixed by SAP. Or maybe could we get access to the sources of sqlod32w.dll 7.6.03.7 to fix it ourselves ?
Thanks,
GuillaumeHello Guillaume
Regarding the threaded access to SQLGetData. Of course, it is possible to manage the syncronization as you proposed. However, I'm still not sure, whether this really solves general problems.
The point is, that the MaxDB-ODBC driver is thread safe for concurrent connections, but not for concurrent statement processing within a single connection. Therefore I would like to ask you how your application accesses data via SQLGetData (due to connections and threads), and what amount of data is usually transfered.
Regards Thomas -
Are static nested classes thread-safe?
There doesn't seem to be any definitive answer to this. Given the following code, is it thread-safe?
public class SomeMultiThreadedWebController {
public HttpServletResponse someMethodToExecuteViaWebRequest(HttpServletRequest request) {
simpleQueryBuilder("SELECT...").addParameter("asdf","asdf").createQuery(EMF.getEntityManager()).executeUpdate();
protected static class SimpleQueryBuilder {
private String queryString;
private Map<String, Object> params = new HashMap<String, Object>();
public SimpleQueryBuilder(String queryString) {
this.queryString = queryString;
public SimpleQueryBuilder addParameter(String name, Object value) {
params.put(name, value);
return this;
public Query createQuery(EntityManager em) {
Query query = em.createQuery(queryString);
for (Entry<String, Object> entry : params.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
return query;
public static SimpleQueryBuilder simpleQueryBuilder(String queryString) {
return new SimpleQueryBuilder(queryString);
}Forget whether or not someone would do this, as this is just an example. I'm really trying to get at whether or not the instance variables inside the static nested class are thread-safe. Thanks for any responses.Hello,
I believe you understand what you're talking about, but you state it in a way that is very confusing for others.
Let me correct this (essentially, incorrect uses of the terminology):
I agree that thread-safe or not is for an operation, for a member, it has some sort of contextual confusion.
Member has a much broader meaning in the [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4] . Even "class member" applies to both an attribute, a method, or an inner class or interface.
I think you mean "member variable" of a class (aka "attribute" or "field"). By the way, static or not is irrelevant to the rest of the discussion.
For an operation or a member, if there's only one thread could access it atomically in one moment, we could call it thread-safe.Mmm. I was tempted to say yes (I'm reluctant to commit myself). With an emphasis on "_The encapsulating class_ makes this member's usage thread-safe".
Still, just synchronizing each operation on a member is not enough to make all usages "thread-safe":
Consider a java.util.Vector: each add/get is synchronized, so it is atomic, fine.
However if one thread adds several values, let's say 3, one by one, to a vector that initially contains 0 values, and another thread reads the vector's size() (another properly synchronized method), the reader thread may witness a size anywhere among 0, 1, 2, 3, which, depending on the business logic, may be a severely inconsistent state.
The client code would have to make extra work (e.g. synchronizing on the vector's reference before the 3 adds) to guarantee that the usage is thread-safe.
Thus any synchronized method(With the limit stated above)
or immutable member (like primitive type) are thread-safe.
Additionally for a member, if it's immutable, then it's thread-safe. You mean, immutable primitive type, or immutable object. As stated previously, an immutable reference to a mutable object isn't thread-safe.
a static final HashMap still have thread-safe issue in practice because it's not a primitive.The underlined part is incorrect. A primitive may have thread-safety issues (unless it's immutable), and an object may not have such issues, depending on a number of factors.
The put, get methods, which will be invoked probably, are not thread-safe although the reference to map is.Yes. And even if the put/get methods were synchronized, the client code could see consistency issues in a concurrent scenario, as demonstrated above.
Additional considerations:
1) read/write of primitive types are not necessarily atomic: section [ §17.7 of the JLS|http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7] explicitly states that writing a long or double value (2 32-bits words) may not be atomic, and may be subject to consistency issues in a concurrent scenario.
2) The Java Memory Model explicitly allows non-synchronized operations on non-volatile fields to be implemented in a "thread-unsafe" way by the JVM. Leading way to a lot of unintuitive problems such as the "Double-Checked Locking idiom is broken". Don't make clever guess on code execution path unless you properly synchronize access to variables across threads.
Edited by: jduprez on Mar 4, 2010 9:53 AM -
Is singleton thread safe?
hello all,
please help me by answering these questions?
singleton patterns calls for creation of a single class that can be shared between classes. since one class has been created
Can singletons be used in a multithreaded environment? is singleton thread safe?
Are threading problems a consequence of the pattern or programming language?
thank you very much,
HiruHi,
Before explaining whether a singleton is thread safe
e i want to explaing what is thread safe here
When multiple threads execute a single instance of a
program and therefore share memory, multiple threads
could possibly be attempting to read and write to the
same place in memory.If we have a multithreaded
program, we will have multiple threads processing the
same instance.What happens when Thread-A examines
instance variable x? Notice how Thread-B has just
incremented instance variable x. The problem here is
Thread-A has written to the instance variable x and
is not expecting that value to change unless Thread-A
explicitly does so. Unfortunately Thread-B is
thinking the same thing regarding itself; the only
problem is they share the same variable.
First method to make a program threadsafe-: Avoidance
To ensure we have our own unique variable instance
for each thread, we simply move the declaration of
the variable from within the class to within the
method using it. We have now changed our variable
from an instance variable to a local variable. The
difference is that, for each call to the method, a
new variable is created; therefore, each thread has
its own variable. Before, when the variable was an
instance variable, the variable was shared for all
threads processing that class instance. The following
thread-safe code has a subtle, yet important,
difference.
second defense:Partial synchronization
Thread synchronization is an important technique to
know, but not one you want to throw at a solution
unless required. Anytime you synchronize blocks of
code, you introduce bottlenecks into your system.
When you synchronize a code block, you tell the JVM
that only one thread may be within this synchronized
block of code at a given moment. If we run a
multithreaded application and a thread runs into a
synchronized code block being executed by another
thread, the second thread must wait until the first
thread exits that block.
It is important to accurately identify which code
block truly needs to be synchronized and to
synchronize as little as possible. In our example, we
assume that making our instance variable a local
variable is not an option.
Third Defence:--Whole synchronization
Here u should implement an interface which make the
whole class a thread safe on or synchronized
Thre views are made by Phillip Bridgham, M.S., is a
technologist for Comtech Integrated Systems.I'm
inspired by this and posting the same hereWas there a point in all of that? The posted Singleton is thread-safe. Furthermore, some of that was misleading. A local variable is only duplicated if the method is synchronized, a premise I did not see established. Also, it is misleading to say that only one Thread can be in a synchronized block of code at any time because the same block may be using different monitors at runtime, in which case two threads could be in the same block of code at the same time.
private Object lock;
public void doSomething() {
lock = new Object();
synchronized(lock) {
// Do something.
}It is not guaranteed that only one Thread can enter that synchronized block because every Thread that calls doSomething() will end up synchronizing on another monitor.
This is a trivial example and obviously something no competent developer would do, but it illustrates that the statement assumes premises that I have not seen established. It would be more accurate to say that only one Thread can enter a synchronized block so long as it uses the same monitor.
It's also not noted in the discussion of local variables vs instance variables that what he says only applies to primitives. When it comes to actual Objects, just because the variable holding the reference is unique to each Thread does not make use of it thread-safe if it points to an Object to which references are held elsewhere.
Maybe you are looking for
-
EA2500 won't connect to my EA3500 Router
I bought a new router today because my WRT54GL was giving me some fits. I purchased an EA3500 and I'm using an EA2500 adapter on the desktop since the router can't reach it via ethernet. Some of my early troubles with this combo began with not being
-
Gmail is not working anymore?
It seems as though after the last update, my Gmail stopped working on the IPhone 4. It just keeps saying "connecting" whenever I click on it and doesn't update my mail. Anyone else experiencing this problem or maybe know what might be wrong? Thanks.
-
TS5223 IPAD does not accept my Apple ID
I have several devices with the same Apple ID. All of them, including this site, accept my AppleID. One of the devices, an IPAD with ios 7, does not accept it. There are other wierd sympthoms, like it refuses to login to facebook suddenly. Is there a
-
Backup to the remote stages is very slow
Hello! I am facing with the following problem for DB Backup to the remote stage. If I plan the ALL ONLINE-Backup, then the backup is takes very slow, backups two or more files and aborts. I have checked the appropriate BTC WP and saw that the WP is
-
How many magnets should the cover on the iPad Smart Case have?
My cover of my iPad Smart Case does not work so well as a stand in landscape mode. I discovered that mine has only 2, 1 in the center and 1 in a corner. Anyone else have this cover and confirm how many magnets theirs has? Wondering if it's a defect o