Old iostreams library re-entrant? thread safe?
We are using -library=iostream to build our product code. Is this old-style iostream library thread safe? or re-entrant?
It looks like we will need to change the iostream header file references to ANSI style (no dot-h) in order to use ANSI iostreams (libCstd or stlport) - is that right?
Thanks,
Evelyn
Evelyn wrote:
What are the trade-offs between using libCstd and stlport?Compatibility and availability:
libCstd is provided as part of Solaris. It is binary compatible across Solaris 8, 9, 10, and Nevada. It is binary compatible for use with all compilers from C++ 5.0 through C++ 5.9 (and the next release when that is availalble).
STLport is shipped as part of the compiler. If you ship an application that uses it, you must also ship libstlport.so.1 as part of your application. (If your application does not use C++ shared libraries, you can link stlport statically instead.)
Standards conformance:
libCstd dates from C++ 5.0, and is not fully standard-conforming. Some valid C++ code will not compile using libCstd, and some features provided as workarounds in libCstd are non-standard and their use is not supported with other libraries.
STLport has good conformance to the C++ Standard, but does not support locales.
More details are in the C++ FAQ:
http://developers.sun.com/sunstudio/documentation/ss12/mr/READMEs/c++_faq.html#LibComp
Similar Messages
-
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. -
Guidlines for a "thread safe" library
I am trying to use a 3rd party library for a communications board (ARINC). I asked the vendor if the library is "thread-safe" since the application is multi-threaded. He had indicated to me he didn't know how to create a thread-safe library. Are there any guidelines i can give him to help him (and eventually me) to write a library that is thread-safe?.
The application uses 5 threads to upload a program or data to a production unit via ARINC communications protocol. (Lane 1 program, Lane 2 program, Progress, Lane 1 cal, Lane 2 cal). If any interruption occurs or a bad checksum in the data flow the unit will lockup and require disassembly and low level j-tag re-programming.Never Mind -
The instrument driver development guide talks about thread protection that can be applied to a library.
Moderator - Please close/delete this topic -
Is the standard C++ library provided in Solaris 9 thread-safe?
Hi,
I cannot find any documentation anywhere that says that the standard C++ library in Solaris 9 (provided by Rogue Wave) is thread safe.
I have seen evidence that makes me think it is not - however, I was wondering if anyone could provide any insight. If they are not, where could I obtain the libraries that are thread safe?
The libraries of interest are:
/lib/sparcv9/libCstd.so.1 &
/lib/sparcv9/libCrun.so.1
Thankyou in advance.Whether the library is thread safe depends on what you mean by thread safety. Except for the 8 standard iostream objects (std::cin, std::cout, etc.), simultaneous accesses from multiple threads to all objects of standard library types must be synchronized by the user. E.g., it's not safe to read or write the same container object (e.g., std::vector, or std::string) from multiple threads at the same time. The C++ localization library imposes some additional restrictions because of its interactions with the global C locale.
-
Is Outside In's PDF Export library's function EXOpenExport thread-safe?
I'm writing a C++ wrapper, for Node.js, around the Outside In PDF Export library, on Ubuntu Linux. Node.js has a single threaded event loop and therefor any long-running processing is done on a worker thread. So, my wrapper is calling all of the PDF Export methods inside of this worker thread. I mention this so that you can be sure of two things: this is a threaded environment, and all PDF Export functions are being called on the same worker thread. Also, I am not making use of any redirected IO or PDF Export-handled threading. I've initialized the library specifying to use no threads. So all of this processing should be occuring within the thread that I call the functions on.
Everything seems to go fine when exporting a single PDF or even maybe two or three in quick succession. When I up the number of PDFs that I try to export to 5+, I receive a SIGSEGV segementation fault from within the OIT libs. The back trace is below:
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff4fd0700 (LWP 1577)]
0x00007fffeef1da26 in HandlePoolCreateHandle () from /usr/local/lib/pdfexport/libwv_core.so
(gdb) bt
#0 0x00007fffeef1da26 in HandlePoolCreateHandle () from /usr/local/lib/pdfexport/libwv_core.so
#1 0x00007fffeef1925d in Win32VCreateHandle () from /usr/local/lib/pdfexport/libwv_core.so
#2 0x00007fffed49046b in WrapBrush(void*, GdiBrush*) () from /usr/local/lib/pdfexport/libos_pdf.so
#3 0x00007fffed46e8c8 in ?? () from /usr/local/lib/pdfexport/libos_pdf.so
#4 0x00007fffed46df63 in GNGetOutputSolutionInfoAt () from /usr/local/lib/pdfexport/libos_pdf.so
#5 0x00007fffeef1e32a in ?? () from /usr/local/lib/pdfexport/libwv_core.so
#6 0x00007fffeef1e214 in ?? () from /usr/local/lib/pdfexport/libwv_core.so
#7 0x00007fffeef18ed3 in Win32VLoadOS () from /usr/local/lib/pdfexport/libwv_core.so
#8 0x00007fffeddffb24 in VwExportOpen () from /usr/local/lib/pdfexport/libex_pagelayout.so
#9 0x00007ffff4062c4d in FAOpenExport () from /usr/local/lib/pdfexport/libsc_fa.so
#10 0x00007ffff7e53270 in EXOpenExport () from /usr/local/lib/pdfexport/libsc_ex.so
#11 0x00007ffff43c0a4d in topdf_convert(uv_work_s*) ()
from /home/ryan/repos/pdf-service/node_modules/topdf/build/Release/topdf.node
#12 0x00000000006e2ec7 in worker (arg=<optimized out>) at ../deps/uv/src/unix/threadpool.c:65
#13 0x00007ffff6fa6e9a in start_thread () from /lib/x86_64-linux-gnu/libpthread.so.0
#14 0x00007ffff6cd3cbd in clone () from /lib/x86_64-linux-gnu/libc.so.6
#15 0x0000000000000000 in ?? ()
I'll explain the back trace a little. The function on #11 is the function inside my code. That is the function in which I call all of the OIT lib functions. The functions on lines #12 and higher are the Node.js-related threading functions, setting up the thread to run my code's function. Functions on lines #10 down to #1 are all the OIT-called functions.
In the documentation for PDF Export, it says that if you're going to be using this library inside a threaded environment, then you need to call the init and deinit functions each time within the worker thread. I'm doing this in my code, which you can see here: https://github.com/ryancole/topdf/blob/master/src/topdf.cc#L29-L74
Is there anything else that I need to be setting that would cause this? I'm only specifying the font directory, explicitly. Are these libraries actually thread-safe? It doesn't look like they are.Well, upon receiving a second opinion on the meaning of the phrasing in the documentation, I have got the library working in a threaded environment now. The first parameter to DEInitEx was supposed to specify to enable PTHREAD support, which I did not have. I thought that it meant something other than it actually does.
-
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. -
Trying to understand "thread-safe" w/ swing components
The other day there was a big hullabaloo about some code I posted because I was calling JLabel.setText from a thread that wasn't the ui thread. On the other hand, this thread was the only thread making changes to the JLabel. My understanding is that in any kind of multi-threaded system, if you just have 1 writer / changer, then no matter how many readers there are, this is thread-safe. So why what I was doing not thread safe?
Second question - JLabel.setText() is essentially setting data in the model for JLabel, which then gets picked up and displayed the next time the GUI thread paints it. So if it's not safe to update a JLabel's model, I assume its never safe to update any data that also is being displayed visually. So for instance, if I was showing some database table data in a JTable, I should do the update in the UI thread - probably not. But what is the distinction?
Third question - what swing components and what operations need to be run on the UI thread to call your program "thread-safe". Validate? setSize()? setLocation()? add? remove? Is there anything that can be called on swing components from a non-ui thread?
Edited by: tjacobs01 on Nov 2, 2008 8:29 PMtjacobs01 wrote:
My understanding is that in any kind of multi-threaded system, if you just have 1 writer / changer, then no matter how many readers there are, this is thread-safe. So why what I was doing not thread safe?This is not true. As I mentioned in that hullabaloo thread, the Java Memory Model allows threads to cache values of variables they use. This means that values written by one thread are not guaranteed to ever be visible to other threads, unless you use proper synchronization.
Take the following example:
import java.util.concurrent.TimeUnit;
public class ThreadExample {
static class Foo {
private String value = "A";
public String getValue() {
return value;
public void setValue(String value) {
this.value = value;
public static void main(String[] args) {
final Foo foo = new Foo();
Thread writer = new Thread() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
foo.setValue("B");
} catch (InterruptedException e) {
e.printStackTrace();
Thread reader = new Thread() {
@Override
public void run() {
try {
TimeUnit.MINUTES.sleep(1);
System.out.println(foo.getValue());
} catch (InterruptedException e) {
e.printStackTrace();
writer.start();
reader.start();
}Here two different threads both access the same Foo instance, which is initialized with a value of "A". One thread, the writer, sleeps one second, and then sets foo's value to "B". The other thread, the reader, sleeps one minute (to avoid race conditions) and then prints foo's value to System.out. It may seem obvious that the reader thread will read the value "B", but this is in fact not guaranteed to be true. The reader thread may never see the value that was written by the writer thread, so it may very well read the old value "A".
(If you run the code you will probably see "B" printed out, but again, this is not guaranteed behavior.)
A simple way to fix this is to synchronize access to the mutable state that the two threads share. For example, change the class Foo to
static class Foo {
private String value = "A";
public synchronized String getValue() {
return value;
public synchronized void setValue(String value) {
this.value = value;
}It's for this same reason that you often see the use of a volatile boolean as a control flag for stopping threads, rather than a plain old boolean. The use of volatile guarantees that the thread you want to stop actually sees the new value of the flag once it has been set by another thread.
Here is an article that touches some of this stuff:
[http://www.ibm.com/developerworks/java/library/j-jtp02244.html]
I also highly recommend the book "Java Concurrency in Practice" (one of the authors of which, David Holmes, sometime hangs out on the Concurrency forum here, I believe).
Edited by: Torgil on Nov 2, 2008 9:01 PM -
How to delete multiple old ITUNES LIBRARY files safely ?
I'd like to clean up my Itunes LIBRARY files, but don't know what's safe to do and not to do. (I have Itunes 8.1 / OSX10.4.11)
MY QUESTION IS TWOFOLD :
(1) how do I create a new Itunes library file now with today's date; and
(2) how do I delete multiple (old) Itunes library files, without risking the loss of what I've got ?
This all stems from exploring Itunes as a result of a problem I had today... when trying to import mp3's from my terrabyte drive, after about 150 successful mp3 track imports, Itunes froze and everything else on my MAC froze as well (constant spinning colored wheel). After many failed attempts to force quit Itunes, I turned off my MBPro. On restarting, Itunes tooks ages to "import" files. Eventually Itunes opened but with only half of my original tunes (1500+ songs 8.11GB) and had nothing from today's import.
I found a post suggesting to hold down OPTION while starting Itunes. Then I selected a file from my hard drive > me > music > Itunes > "Itune library" with the most recent date and shezam, Itunes once again has all my songs, as before. Nothing I imported from the terrabyte drive today appears however, but no matter.
In my "Itunes" file there appear MULTIPLE Itunes libraries ! such as Itunes library, Itunes Library (damaged), and as well a folder called "Previous Itunes Libraries" which itself contains multiple Itunes Library files and multiple "previous Itunes Library files" with dates back to 2007. These I want to clean up and delete .... should I ? ... Can I ?
I really could use some words of wisdom from the wise ! Thanks in advanceWhenever you install a new version of iTunes and run it teh first time, iTunes will create a backup of the current iTunes library file and copy it into \Music\iTunes\Previous iTunes libraries, then update the iTunes library file in \Music\iTunes\ for the current version of iTunes.
-
I am an older novice user. I gave my Itouch to my duaghter....and took her Ipod Classic 64.....have used and played the songs but not updated in a couple years. The laptop I set the account up from died and I downlowded the new 10.6 software onto this PC. /When i signed in to my account I cannot seem to find a place to find my old library. I had more music and movies on the library than on the Ipod classic....was hoping to find it all before i sync up again.
Any tips on how to find or access the old library or did I lose it with the old laptop? LOL...a confused oldie....would like tomove music to my Iphone once all is found and resumed.
Thanks in advance for any insight or suggetions.The old iTunes library was lost with the old PC. However, it all that music and content is still on your iPod there are many ways you can extract this content from the iPod and import it back into iTunes.
Your iPod is designed to sync with only one iTunes library at a time. It will recognize the iTunes library on the new PC as a new library. If you sync the iPod with this new library, all content will be erased from the iPod and replaced with what is in the new library. So what you will want to do is copy everything from the iPod to your new iTunes library on your PC first.
See this older post from another forum member Zevoneer covering the different methods and software available to assist you with the task of copying content from your iPod back to your PC and into iTunes.
https://discussions.apple.com/thread/2452022?start=0&tstart=0
B-rock -
Trouble importing old photo library to iPhoto 06
I just updated to iLife/iPhoto 06. When importing old photo library which is 7-8,000 photos, I got 24,000 + images incl. images of computer icons, demo photos, images that look like pieces from web pages (headers, part of photos etc), 4-5 copies of my own photos, some look like they are "pixilated", which the original wasn't. Any idea of what happened and how to fix this, short of manually deleting each image that doesn't belong?
iMac G5 Mac OS X (10.4.9)Terence,
Tks, I kind of suspected that. I'm new to Macs and more used to PCs, and by no means good at either system, so it sometimes gets confusing.
Anyway - Here's the list from the iPhoto Library folder - I did copy & paste, but it didn't paste in the same order it is listed in the iPhoto Library window. I guess it should all be there though.
CIMG0933.JPG
01000008.JPG
CIMG0991.JPG
CIMG0985.JPG
CIMG0984.JPG
CIMG0981.JPG
CIMG1309.JPG
IMG_0703.JPG
IMG_0704.JPG
IMG_0705.JPG
IMG_0706.JPG
iPhoto.ipspot
iPod Photo Cache
Library6.iPhoto
CIMG1307.JPG
CIMG1308.JPG
CIMG1312.JPG
CIMG1313.JPG
CIMG1314.JPG
CIMG1315.JPG
CIMG1316.JPG
CIMG1317.JPG
IMG_0682.JPG
IMG_0683.JPG
IMG_0684.JPG
IMG_0685.JPG
IMG_0686.JPG
IMG_0687.JPG
IMG_0688.JPG
IMG_0689.JPG
IMG_0690.JPG
IMG_0691.JPG
IMG_0692.JPG
IMG_0693.JPG
IMG_0694.JPG
CIMG1286.JPG
CIMG1291.JPG
CIMG1285.JPG
D.CTG
Data
Dir.data
IMG_0645.JPG
IMG_0646.JPG
IMG_0647.JPG
IMG_0648.JPG
IMG_0649.JPG
IMG_0650.JPG
IMG_0652.JPG
IMG_0653.JPG
IMG_0654.JPG
IMG_0655.JPG
IMG_0695.JPG
IMG_0696.JPG
IMG_0697.JPG
IMG_0698.JPG
IMG_0699.JPG
IMG_0700.JPG
IMG_0701.JPG
IMG_0702.JPG
IMG_0677.JPG
IMG_0678.JPG
IMG_0679.JPG
iPhotoLock.data
Library.data
Library.iPhoto
MauiJan.2006055 Folder.2
Modified
Originals
Richardito politicing
scan-2.jpg
Thumb32Segment.data
Thumb64Segment.data
ThumbJPGSegment.data
CIMG1005.JPG
CIMG1006.JPG
CIMG1007.JPG
CIMG1008.JPG
CIMG1009.JPG
CIMG1010.JPG
CIMG1011.JPG
CIMG1024.JPG
CIMG1025.JPG
CIMG1026.JPG
CIMG1027.JPG
CIMG1028.JPG
CIMG1029.JPG
CIMG1030.JPG
CIMG1035.JPG
CIMG1277.JPG
CIMG1278.JPG
CIMG1279.JPG
CIMG1280.JPG
CIMG0965.JPG
CIMG0966.JPG
CIMG0967.JPG
CIMG0968.JPG
CIMG0969.JPG
CIMG0970.JPG
CIMG0971.JPG
CIMG0972.JPG
CIMG0973.JPG
CIMG0975.JPG
CIMG0976.JPG
CIMG0977.JPG
CIMG0978.JPG
IMG_0643.JPG
CIMG0979.JPG
CIMG0980.JPG
CIMG0960.JPG
CIMG0961.JPG
CIMG0962.JPG
CIMG0963.JPG
CIMG0964.JPG
IMG_0681.JPG
CIMG0988.JPG
CIMG0989.JPG
CIMG0987.JPG
CIMG0929.JPG
IMG_0675.JPG
IMG_0680.JPG
CIMG1300.JPG
CIMG1301.JPG
CIMG1302.JPG
CIMG1303.JPG
CIMG1292.JPG
CIMG1293.JPG
CIMG1294.JPG
CIMG1295.JPG
CIMG1296.JPG
CIMG1297.JPG
IMG_0661.JPG
IMG_0668.JPG
IMG_0670.JPG
IMG_0672.JPG
IMG_0673.JPG
IMG_0708.JPG
IMG_0709.JPG
01000022.JPG
CIMG0982.JPG
IMG_0658.JPG
CIMG1034.JPG
CIMG0943.JPG
CIMG1281.JPG
01000007.JPG
CIMG0997.JPG
CIMG1287.JPG
CIMG0930.JPG
CIMG1017.JPG
01000001.JPG
CIMG0999.JPG
CIMG0923.JPG
CIMG1284.AVI
CIMG0917.JPG
CIMG0935.JPG
IMG_0666.JPG
IMG_0707.JPG
CIMG1282.JPG
2001
CIMG0916.JPG
CIMG0950.JPG
CIMG1000.JPG
CIMG0931.JPG
CIMG0918.JPG
CIMG0941.JPG
CIMG1306.JPG
CIMG0913.JPG
CIMG0944.JPG
01000004.JPG
CIMG0920.JPG
CIMG0998.JPG
01000017.JPG
CIMG0942.JPG
CIMG1289.JPG
01000005.JPG
1999
CIMG1023.JPG
CIMG0986.JPG
01000014.JPG
01000011.JPG
IMG_0662.JPG
2000
2004
IMG_0710.JPG
IMG_0659.JPG
CIMG0953.JPG
CIMG1018.JPG
2002
IMG_0671.JPG
CIMG0932.JPG
106.CTG
CIMG0952.JPG
CIMG1022.AVI
CIMG0937.JPG
CIMG1019.JPG
CIMG1288.JPG
01000021.JPG
107.CTG
01000027.JPG
CIMG0983.JPG
CIMG0947.JPG
AlbumData.xml
CIMG0992.JPG
CIMG1032.JPG
CIMG0957.JPG
01000002.JPG
CIMG1020.JPG
CIMG0958.JPG
01000009.JPG
2007
CIMG0959.JPG
CIMG1001.JPG
01000023.JPG
CIMG0928.JPG
01000020.JPG
CIMG0934.JPG
01000003.JPG
IMG_0676.JPG
IMG_0660.JPG
01000012.JPG
2006
CIMG1033.JPG
CIMG0911.JPG
1969
CIMG0919.JPG
CIMG1283.JPG
CIMG0938.JPG
01000026.JPG
2003
CIMG0940.JPG
01000010.JPG
01000019.JPG
CIMG0925.JPG
2005
01000025.JPG
CIMG1290.JPG
CIMG0951.JPG
CIMG1021.JPG
CIMG1013.JPG
CIMG0915.JPG
CIMG1012.JPG
01000024.JPG
CIMG0994.JPG
01000013.JPG
CIMG0948.JPG
CIMG0993.JPG
CIMG1031.JPG
01000006.JPG
CIMG0939.JPG
CIMG0910.JPG
CIMG0914.JPG
CIMG1016.JPG
CIMG0909.JPG
CIMG0949.JPG
CIMG0924.JPG
01000018.JPG
CIMG0946.JPG
CIMG0945.JPG
CIMG0936.JPG
CIMG1015.JPG
01000015.JPG
CIMG0926.JPG
CIMG0921.JPG
CIMG0912.JPG
01000016.JPG
CIMG0927.JPG
CIMG0996.JPG
CIMG0922.JPG
04
08
By the way, here's another question, a bit off the current subject: Sometimes we have trouble playing video clips downloaded from our camera. Sometimes iPhoto will play the audio but no picture, sometimes the other way around, and there don't seem to be any common thread one way or the other. Recently a bunch of clips that used to play audio only "repaired themselves" and are not playing fine. But others are only playing video with no sound. Any idea of whats going on?
Thanks
Marianne -
Hi
This code is currently running on my companys server in a java class implementing the singleton pattern:
public static ShoppingAssistant getInstance() {
if (instance == null) {
synchronized (ShoppingAssistant.class) {
instance = new ShoppingAssistant();
return instance;
}1 Is there really a need for synchronizing the method?
2 If you choose to synchronize it. Why not just synchronize the whole method?
3 Is this method really thread safe? Is I see it a thread A could be preempted after checking the instance and seing that it is null. Thereafter another thread B could get to run, also see that instance is null and go on and create the instance. Thereafter B modifies some of the instance�s instance variables. After that B is preempted and A gets to run. A, thinking instance is null, goes on and create a new instance of the class and assigns it to instance, thus owerwriting the old instance and creating a faulty state.
By altering the code like this I think that problem is solved although the code will probably run slower. Is that correct?
public static ShoppingAssistant getInstance() {
synchronized (ShoppingAssistant.class) {
if (instance == null) {
instance = new ShoppingAssistant();
}Regards, Mattiaspublic class Singleton {
private static final instance = newSingleton();
public static Singleton getInstance() {
return instance;
}This seems like it's so obviously the standard
solution, why do
people keep trying to give lazy solutions? Do they
expect it to be
more efficient that this?I can see one possible performance gains with a lazy solution:
If you use something else in that class (besides getInstance()), but don't use getInstance, then you don't take the performance hit of instantiating the thing.
Of course, this is dubious at best because how often do you have other static methods in your singleton class? And not use the instance? And have construction be so expensive that a single unnecessary one has a noticeably detrimental impact on your app's performance? -
Thread safe RMI.
My RMI server provides clients with the ability to CRUD data but in order to manage concurrency I did the following.
1stly I would like to understand correctly the issues of RMI server objects....
It is my understanding that RMI server can cater for eg 100 clients by spawning 100 threads at random for each client. This process is not managed (thread wise) and the result is that 20 clients wishing to update record A can do so at will? Various steps can be taken from what I gather...
a) Synchronise (expensive)
b) implement a lock manager.
The step I have taken is include a lock manager and I have ensured that all locking an unlocking occur in a singleton server object that manages all sensitive data CRUD operations. Now I use a lock manager but I would like to know what happens if for eg the 1st RMI client dies and has its thread blocking
all other threads from locking the same record? Does the thread die with the client or is there a counter measure for this? The obvious answer that comes to mind is Object.wait() inside the lock manager?
The reason I ask was that because all of the locking occurs in a single method call in the Network
Server's JVM, so is there a need to worry about the RMI connection dying during the middle the locking operation.
Edited by: Yucca on May 23, 2009 8:14 PM/*
* @(#)LockManager.java
* Version 1.0.0
* 27/03/2009
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import java.util.ResourceBundle;
class LockManager {
* The <code>Map</code> containing all the record number keys of currently
* locked records that pair with the cookie value assigned to them when they
* are initially locked.
private static Map<Integer, Long> currentlyLockedMap =
new HashMap<Integer, Long>();
private static final Logger LOG = Logger.getLogger("project.db");
* Locks a record so that it can only be updated or deleted by this client.
* Returned value is a <code>long</code> that is the cookie value that must
* be used when the record is unlocked, updated, or deleted.
* If the specified record is already locked by a different client, then the
* current thread gives up the CPU and consumes no CPU cycles until the
* record is unlocked.
* @param recNo the assigned primary key of the record
* to be locked for an operation.
* @param data a <code>Data</code> instance used to
* check if the record exists before
* attempting the lock operation.
* @return A <code>long</code> containing the
* cookie value that must be used when the
* record is unlocked.
* @throws RecordNotFoundException if specified record does not exist or if
* specified record is marked as deleted
* in the database file.
long lock(int recNo, DB data) throws RecordNotFoundException {
LOG.entering(this.getClass().getName(), "lock", recNo);
synchronized (currentlyLockedMap) {
try {
while (currentlyLockedMap.containsKey(recNo)
&& currentlyLockedMap.get(recNo)
!= Thread.currentThread().getId()) {
currentlyLockedMap.wait();
// Check if record exists.
data.read(recNo);
long cookie = Thread.currentThread().getId();
currentlyLockedMap.put(recNo, cookie);
LOG.fine("Thread " + Thread.currentThread().getName()
+ "got Lock for " + recNo);
LOG.fine("Locked record count = " + currentlyLockedMap.size());
LOG.exiting(this.getClass().getName(), "lock", true);
return cookie;
} catch (InterruptedException ie) {
throw new SystemException("Unable to lock", ie);
* Releases the lock on a record. The cookie must be the cookie returned
* when the record was locked.
* @param recNo the assigned primary key of the record
* to be unlocked after an operation.
* @param cookie the cookie returned when the record was
* locked.
* @throws RecordNotFoundException if specified record does not exist or if
* specified record is marked as deleted
* in the database file.
* @throws SecurityException if the record is locked with a cookie
* other than cookie.
void unlock(int recNo, long cookie) throws RecordNotFoundException,
SecurityException {
LOG.entering(this.getClass().getName(), "unlock",
new Object[] { recNo, cookie });
synchronized (currentlyLockedMap) {
checkLock(recNo, cookie);
currentlyLockedMap.remove(recNo);
LOG.fine("released lock for " + recNo);
currentlyLockedMap.notifyAll();
LOG.exiting(this.getClass().getName(), "unlock");
* Checks if the given record is locked before doing any modification or
* unlocking for the record.
* <p/>
* Checks the <code>Map</code> of record number keys and cookie values
* to see if it contains the given record number.
* @param recNo the assigned primary key of the record
* to be checked if it is locked.
* @param lockCookie the cookie returned when the record was
* initially locked.
* @throws SecurityException if no lock exists for the record or if
* the record has been locked with a
* different cookie.
void checkLock(int recNo, long lockCookie) throws SecurityException {
LOG.entering(this.getClass().getName(), "checkLock",
new Object[] { recNo, lockCookie });
// Check if record has been locked
if (!currentlyLockedMap.containsKey(recNo)) {
throw new SecurityException(ResourceBundle.getBundle(
"resources.ErrorMessageBundle").getString(
"lockNotAppliedKey"));
// Check if record has been locked by different cookie.
if (currentlyLockedMap.get(recNo) != lockCookie) {
throw new SecurityException(ResourceBundle.getBundle(
"resources.ErrorMessageBundle").getString(
"notLockOwnerKey"));
LOG.exiting(this.getClass().getName(), "checkLock");
}Edited by: Yucca on May 23, 2009 8:16 PM
Edited by: Yucca on May 23, 2009 8:18 PMIt is my understanding that RMI server can cater for eg 100 clients by spawning 100 threads at random for each client.No. It spawns a new thread for every new connection. At the client end, RMI makes a new connection for every call unless it can find an idle connection to the same host that is less than 15 seconds old. So if the client is doing concurrent calls there will be concurrent threads at the server for that client.
This process is not managed (thread wise)'Managed' meaning what?
the result is that 20 clients wishing to update record A can do so at will?The result is that an RMI server is not thread safe unless you make it so.
a) Synchronise (expensive)Compared to a database update the cost of synchronization is trivial.
b) implement a lock manager. The database should already have one of those, and so does java.util.concurrent. Don't write your own. Personally I would just syncrhonize around the database calls.
what happens if for eg the 1st RMI client dies and has its thread(a) the client doesn't have a thread, see above. The call has a thread.
(b) at the server, the call will execute, regardless of the state of the client, until it is time to write the result back to the client, at which point the write will encounter an IOException of some description and the thread will exit.
blocking all other threads from locking the same record?That can't happen unless you foul up your concurrency management.
Does the thread die with the clientIt dies with the call.
is there a need to worry about the RMI connection dying during the middle the locking operation.The server JVM won't notice until it is time to write the call result back, see above. -
Hello,
I have an BC4J-based application, based on BC4J9.0.2. I'm considering to upgrade my BC4J library to upper version to make my application more thread-safe.
How can I make thread-safe application using BC4J? Is there any specific Rule?
Thank you.Hi,
Its hard to define a single rule since it depends upon how each application is using threads. I have included some thoughts about the most common scenarios for web clients below:
The BC4J client wizards (datatags, struts, JClient) will help you generate threadsafe applications. The general rule when writing a web client is to ensure that each "user", as represented by an HttpSession instance, has their own ApplicationModule instance. Using the ApplicationModule datatag or the BC4J/Struts framework will guarantee this.
Beyond this it may also be necessary to coordinate multiple concurrent requests from a single client (imagine a user pounding on the browser refresh button). One approach for solving this problem is to synchronize requests on some sort of session context. The ApplicationModule tag supports a latching mode (see the lock attribute) which performs this by synchronizing access to the SessionCookie (cached in session, used to acquire ApplicationModule instance). Support for latching will also be available in Struts in the 9.0.3.3 and later timeframe.
Hope this helps, -
Repaint() is not thread-safe?
I saw a description that says repaint() is thread-safe in an old swing tutorial, but not in the current tutorial and its javadoc. So can I assume repaint() is not thread-safe and I should call it from EDT? ... Or if they are thread-safe, why does Sun not document it?
repaint() calls paint() on EDT... but it calculates dirty region on the current thread and does not get AWTTreeLock.I don't think so.
repaint() is a java.awt.Component method and doesn't know about Swing's RepaintManager and dirty regions. There may be somthing similar at the AWT level that escaped me, but looking at the JDK1.6 source code, java.awt.Component.repaint() just repaints the whole component.
Now repaint(long, int, int, int, int) has two versions.
At the AWT level, it just posts a paint event for the specified region. No race condition, and no risk that he region be wrong, but possibility to invoke multiple paint(Graphics) that overlap, that is, to paint several times the same area - it may be an optimization problem, but it doesn't jeopardize the consistency of the drawing.
At the Swing level, it does compute dirty regions. In Repaint manageer, the call to extendDirtyRegion(...) is protected within a synchronized block, but the code before that is not. From a quick look, that code is:
1) walking up the component hierarchy to find the root, which may not be thread-safe, but a well-behaved application shouldn't change the hierarchy from outside the EDT.
2) walking up a chain of "delegate" RepaintManager, which I knew nothing about... Apparently it's a sun's implementation specific construct, each JComponent can be assigne d a delegate RepaintManager. Again I would claim that such things should not happen outside of the EDT, but I haven't found documentation about this.
Edited by: jduprez on Jul 20, 2009 2:37 PM
so no, technically, I can't prove repaint(long, int,int,int,int) is thread-safe.
But a well-behaved application that updates its widgets on the EDT shouldn't worry (that is, repaint(...) calls can still be invoked outside of the EDT).
Edited by: jduprez on Jul 21, 2009 7:04 PM - typos -
SortedSet thread-safe howto?
Hello,
i m trying to acces SortedSet with multiple thread, but i can't
here is my code :
public class Test {
static SortedSet queue = Collections.synchronizedSortedSet((SortedSet) new TreeSet());
static Vector v = new Vector();
public static Vector getV() { return v;}
public static SortedSet getQueue () {
return queue;
public static void main(String[] args) throws Exception {
launchFrame();
for (int i=0; i<2; i++) {
new SimpleThread2("thread"+i).start();
public static void end() {
System.out.println(v.size()+" lalala "+queue.size());
class SimpleThread2 extends Thread {
int j = 0;
public SimpleThread2(String str) {
super(str);
public void run() {
for (int i = 0; i < 10; i++) {
try {
SortedSet s = Test.getQueue();
synchronized (s) {
s.add(new String(""+i));
Test.getV().add(""+i);
} catch (Exception ex) {ex.printStackTrace();}
Test.end();
here is my result :
10 lalala 10
20 lalala 10
as u can see Vector is thread safe but SortedSet not....That has nothing to do with Thread-safe or not. A Set be it sorted or not always only contains at most one reference to a specific Object as long as equals() and compareTo() are implemented properly.
In the second run you add identical Strings to both the SortedSet and the Vector. In the SortedSet, they replace the old entries and in the Vector, they are appended as the Vector is a List and allows multiple identical entries.
Maybe you are looking for
-
App Loader tell me "No New found for this device" or something like that
I've been going around and around with this issue - I know that in addition to the DM, I need tohave the OS installed on my laptop. So, I've installed, uninstalled, etc.., etc, deleted teh Vendor xml. pulled the battery and put it back in - still get
-
My original itunes account was set up with a work email, so when I left the company, I contacted support to have a new user name and transfer the library. Now each time I synch, it is trying to match up to the original purchase from the original acc
-
"HKONT is empty" error message is getting while doing MIRO
Hi Gurus While i am doing MIRO, i am getting the error message of "HKONT is empty". What is this error & how can i resolve and where can i check this G/L Account belongs to what? Thanks in adv, Regards BADRI
-
Connecting to wifi with wap security?
I need help i have the pearl 8130 and the wireless at my office is WAP secured, I can not figure out how to connect to it, the network is not hidden, my laptop picks it up just fine, but the phone cant even find it. I know the ssid and when I enter
-
I want to do the following <% response.setContentType("text.xsl"); String something = ""+<xsl:value-of select='@id' />+""; %> But seems like the xsl doesn't render Can someone point me in he right directions