Java.util.Locale not thread-safe !

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

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

Similar Messages

  • Java.util.zip.ZipFile is not thread-safe?

    I didn't find any notes in its javadoc.
    Actually I want to know whether ZipFile.getInputStream(ZipEntry) method is thread-safe. As I mentioned there is no information in the javadoc but I suppose that ZipFile is not thread-safe.
    Am I right?

    More classes are safe if you don't attempt to change
    anything. However if you change the ZIP file while
    attempting to read it, forget it.I doubt that you can read any 'file' without 'changing' something.
    Low level file io almost always uses buffers. I am not even sure if modern operating systems allow byte access to files on the hard drive anymore. And buffers are modified when they are read.

  • Can not create WebService with java.util.Locale object why?

    I am unable to create a WebService which contains a Locale Object in the request.  I assume its because the java.util.Locale object is not Serializable.  Can anyone tell me if there is a work around for this?

    Hi,
    Make sure your strings for Locale follow these rules...
    The language string should be lower-case, two-letter codes as defined by ISO-639.
    http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt
    The country string should be upper-case, two-letter codes as defined by ISO-3166.
    http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
    Or try with some constant Locales like
    Locale.CANADA
    Locale.US
    regards,
    Uma

  • Coherence SimpleParser class is not thread safe?

    Coherense has very convinent XML utility class, which we use it a lot within our Coherence related applications.
    But we encounter some mysterious lock up (maybe deadlock?) issue and identified that it might be that the com.tangosol.run.xml.SimpleParser class is not thread safe.
    We are using tomcat 6 and spring 2.0.6.
    One of the webapp has 2 bean which implements InitializingBean interface.
    Bean A's afterPropertiesSet() method will use com.tangosol.run.xml.XmlHelper.loadXml method to parse a XML file.
    Bean B's afterPropertiesSet() method will acts as a tcp extend client and retrieve some data from a coherence cluster. Which I believe coherence will also use it's XML utility class when parsing the configuration files.
    We encounter tomcat lockup (which never finish startup webapp deployment porcess) randomly like 1 out of 2 or 3 tries.
    Use jconsole and connect to tomcat we can see that the main thread stuck in SimpleParser class. Here is the thread dump.
    Name: main
    State: RUNNABLE
    Total blocked: 156 Total waited: 0
    Stack trace:
    com.tangosol.run.xml.SimpleParser.instantiateDocument(SimpleParser.java:150)
    com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:115)
    - locked com.tangosol.run.xml.SimpleParser@f10c77
    com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:71)
    com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:84)
    com.tangosol.run.xml.XmlHelper.loadXml(XmlHelper.java:109)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1201)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1171)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:425)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
    - locked java.util.concurrent.ConcurrentHashMap@dee55c
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:287)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
    - locked java.lang.Object@d21555
    org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:244)
    org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:187)
    org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:49)
    org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3830)
    org.apache.catalina.core.StandardContext.start(StandardContext.java:4337)
    - locked org.apache.catalina.core.StandardContext@1c64ed8
    org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
    - locked java.util.HashMap@76a6d9
    org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
    org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
    org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:825)
    org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:714)
    org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:490)
    org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
    org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
    org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    - locked org.apache.catalina.core.StandardHost@1c42c4b
    org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
    - locked org.apache.catalina.core.StandardHost@1c42c4b
    org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    - locked org.apache.catalina.core.StandardEngine@37fd24
    org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    org.apache.catalina.core.StandardService.start(StandardService.java:516)
    - locked org.apache.catalina.core.StandardEngine@37fd24
    org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    - locked [Lorg.apache.catalina.Service;@1cc55fb
    org.apache.catalina.startup.Catalina.start(Catalina.java:566)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
    After we add the depends-on tag to enforce bean B wait on bean A to finish initialization, we no longer encounter the lockup during tomcat startup.
    We suspect that maybe SimpleParser class is not thread safe and will cause potential deadlock issue.
    Edited by: user639604 on Jun 22, 2009 10:36 AM

    While it doesn't show up as deadlock, I believe it probably is, as evidenced by these two threads:
    "Timer-0" prio=10 tid=0xcb9a2800 nid=0x454b in Object.wait() [0xcb6e0000..0xcb6e10a0]
       java.lang.Thread.State: RUNNABLE
         at com.tangosol.run.xml.SimpleParser.instantiateDocument(SimpleParser.java:150)
        at com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:115)
         - locked <0xf44e52f0> (a com.tangosol.run.xml.SimpleParser)
         at com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:71)
         at com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:99)
         at com.tangosol.run.xml.XmlHelper.loadXml(XmlHelper.java:129)
         at com.tangosol.run.xml.XmlHelper.loadXml(XmlHelper.java:95)
         at com.tangosol.run.xml.XmlHelper.loadXml(XmlHelper.java:72)
         at com.tangosol.util.ExternalizableHelper.<clinit>(ExternalizableHelper.java:4466)
         at com.evidentsoft.opcache.coherence.OPCacheCoherenceStorage.retrieve(OPCacheCoherenceStorage.java:341)
         at com.evidentsoft.opcache.coherence.OPCacheCoherenceStorage.retrieve(OPCacheCoherenceStorage.java:420)
         at com.evidentsoft.opcache.OPCacheManager.find(OPCacheManager.java:68)
         at com.evidentsoft.logserver.coherence.ClusterDetector.detectNewClusters(ClusterDetector.java:97)
         at com.evidentsoft.logserver.coherence.ClusterDetector.access$000(ClusterDetector.java:19)
         at com.evidentsoft.logserver.coherence.ClusterDetector$1.run(ClusterDetector.java:67)
         at java.util.TimerThread.mainLoop(Unknown Source)
         at java.util.TimerThread.run(Unknown Source)
    "main" prio=10 tid=0x08059000 nid=0x4539 in Object.wait() [0xf7fd0000..0xf7fd11f8]
       java.lang.Thread.State: RUNNABLE
         at com.tangosol.run.xml.SimpleParser.instantiateDocument(SimpleParser.java:150)
         at com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:115)
         - locked <0xf44ecd90> (a com.tangosol.run.xml.SimpleParser)
         at com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:71)
         at com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:84)
         at com.tangosol.run.xml.XmlHelper.loadXml(XmlHelper.java:109)
         at com.evidentsoft.coherence.util.ClusterConfigurator.generateConfigFile(ClusterConfigurator.java:319)
         at com.evidentsoft.coherence.util.ClusterConfiguratorProxy.afterPropertiesSet(ClusterConfiguratorProxy.java:51)
         at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1201)
         at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1171)
         at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:425)
         at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
         at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
         - locked <0xd65efb88> (a java.util.concurrent.ConcurrentHashMap)
         at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
         at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
         at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:287)
         at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
         - locked <0xd65efc28> (a java.lang.Object)
         at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:244)
         at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:187)
         at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:49)
         at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3830)
         at org.apache.catalina.core.StandardContext.start(StandardContext.java:4337)
         - locked <0xd6092f60> (a org.apache.catalina.core.StandardContext)
         at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
         - locked <0xd54ff278> (a java.util.HashMap)
         at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
         at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
         at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:825)
         at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:714)
         at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:490)
         at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
         at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
         at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
         at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
         - locked <0xd54ff1e8> (a org.apache.catalina.core.StandardHost)
         at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
         - locked <0xd54ff1e8> (a org.apache.catalina.core.StandardHost)
         at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
         - locked <0xd4fa60b8> (a org.apache.catalina.core.StandardEngine)
         at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
         at org.apache.catalina.core.StandardService.start(StandardService.java:516)
         - locked <0xd4fa60b8> (a org.apache.catalina.core.StandardEngine)
         at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
         - locked <0xd4f17ea0> (a [Lorg.apache.catalina.Service;)
         at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
         at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)The reason it isn't showing up as a deadlock in the thread dump is that the ExternalizableHelper static initializer isn't completing, so the other thread (blocking it) is waiting indefinitely on that class to become available.
    Peace,
    Cameron Purdy | Oracle Coherence

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

  • WS endpoints restricition: What about java.util.Locale etc.?

    We have some problems with the restrictions for WS endpoints.
    Using SAPNW Developer Studio to create a web service including the virtual interface from a stateful session bean, we are not allowed to use usual types like java.util.Locale or java.util.Properties although they are serializable.
    This is also decribed in the SAPNW DS Help:
    "The following types are not allowed anywhere in the endpoint of a Web service:
    ·        Remote objects (EJBs)
    ·        Classes extending into another class and implementing an interface
    ·        Hashed table-like types
    ·        Classes/objects that cannot be serialized"
    So what is the preferred solution for this issue?
    Is there a way to use the serializable java.util.Locale type in a WS endpoint, or do we have to use its String representation?
    What is the preferred solution for hash-table types like Properties? And what about Interface types like Map?
    Maybe we just do not find the decisive documentation link?
    Thanks a lot,
    Dirk
    Edited by: Dirk Weigand on Nov 20, 2008 8:48 AM
    Moved to "Application Server - Java Programming"

    Question moved to "Java Programming"

  • Java.lang.reflect.Constructor thread safe ?

    When you have a Constructor object in Java.
    Is calling the newInstance method on the same Constructor object from multiple threads safe.
    Or is this not thread safe leading to wrongly constructed objects?

    ejp wrote:
    And as Constructors are immutable, it's hard to see how it's going to get altered.Constructors are basically immutable, but they have at least one state which can make the difference between newInstance working or failing.
    As you can see in the following example, setAccessible() is not something you would want to set to different values in different threads.
    import java.lang.reflect.Constructor;
    public class Main {
        public static void main(String... args) throws Exception {
            Constructor cons = Private.class.getDeclaredConstructor();
            cons.setAccessible(false);
            try {
                System.out.println("cons.isAccessible()= " + cons.isAccessible());
                cons.newInstance();
                throw new AssertionError("IllegalAccessException expected");
            } catch (IllegalAccessException expected) {
                // ignored
            cons.setAccessible(true);
            System.out.println("cons.isAccessible()= " + cons.isAccessible());
            cons.newInstance();
    class Private {
        private Private() {
    }

  • 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

  • Error:Class java.util.date not found

    i have installed 9iAS on my computer.And i want to develop program on JSP.i tried the url below
    http://eyuksel/servlet/IsItWorking
    and i got "it is working" message.when i try to execute my first jsp file i get the error:
    Errors compiling:d:\ias\apache\apache\htdocs\_pages\\_first.java
    d:\ias\apache\apache\htdocs\_pages\_first.java:55: Class java.util.date not found.
    out.print( new java.util.date() );
    ^
    1 error
    what must i do or how can i install the java classes.
    kind regards...
    null

    Thank you very much.It worked:)
    Java is case-sensitive.
    try
    java.util.Date
    instead of
    java.util.date
    null

  • HTTP request/response object not thread safe.

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

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

  • JTextArea: Not thread safe

    I am working on a lobby system with a chat are using Networking, and recently I noticed that occasionally my JTextArea does not append the data I give it, even if I have a System.out.println() directly before which shows me what it is being passed, and it is being passed correct Strings, it is just not appending them.
        Thread updateText = new Thread() {
            public void run()
                for(;;)
                    try {
                        for (int x = 0; x < texts.size(); x++) {
                            System.out.println("ADDED: "+texts.get(x));
                            textArea.append(texts.get(x));
                        texts.clear();
                        scrollToEnd(textArea);
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        };I have an ArrayList texts, which keeps track of what is being typed into the Chat Area. This code displays correctly What I want it to, i.e. "ADDED: Hello guys, etc.", however the JTextArea does not update. Is there something to make the JTextArea thread-safe because I have heard on several sites that JTextAreas are not thread-safe.
    Any help would be greatly appreciated.

    I changed my code to this: and now it does not work at all, i.e., the JTextArea never updates:
        Thread updateText = new Thread() {
            public void run()
                for(;;)
                    try {
                        SwingUtilities.invokeAndWait(update);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (InvocationTargetException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        Runnable update = new Runnable() {
            public void run()
                try {
                    texts.clear();
                    scrollToEnd(textArea);
                    for (int x = 0; x < texts.size(); x++) {
                        System.out.println("ADDED: " + texts.get(x));
                        textArea.append(texts.get(x));
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        };

  • What does, "swing is not thread safe." mean?

    can anyone explain what that means in detail?

    [Google can|http://letmegooglethatforyou.com/?q=swing+is+not+thread+safe+tutorial]
    For better response, you may wish to ask a specific question that's answerable without having to write a book chapter.

  • Formatting Negative Currency using the Java.Util Locale

    Hi....
    I am using the Locale file to get the currency code of a specified country. The code is given below.
    public String setCurrency(String _currency){
    Locale locale = new Locale("","PG");
    NumberFormat format = NumberFormat.getCurrencyInstance(locale);
    this.currency = format.format(Double.parseDouble(_currency));
    return currency;
    When i pass a negative value as the currency (-200) the string which returns will be as (PGK200) and when i pass a positive value it will be as PGK200......
    How can i format this so that when i pass a negative value, the returned String will be -PGK200 ??
    If there is anyone who knows how i can get this done please reply soon....
    Thanks in advance.
    Regards
    Nuwan.

    Check this out:import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.util.Locale;
    public class CurrencyEg {
        private String currency;
        public String setCurrency(String _currency){
            Locale locale = new Locale("","PG");
            //NumberFormat format = NumberFormat.getCurrencyInstance(locale);
            DecimalFormat format = (DecimalFormat)NumberFormat.getCurrencyInstance(locale);
            format.setNegativePrefix("-PKG");
            format.setNegativeSuffix("");
            format.setPositivePrefix("PKG");
            format.setPositiveSuffix("");
            format.setMaximumFractionDigits(0);
            this.currency = format.format(Double.parseDouble(_currency));
            return currency;
        public static void main(String args[]) {
            CurrencyEg eg = new CurrencyEg();
            System.out.println("200 -> " + eg.setCurrency("200"));
            System.out.println("-200 -> " + eg.setCurrency("-200"));
    }I don't know how valid it is to cast and mess about with the format - but it gives exactly the output you were after:200 -> PKG200
    -200 -> -PKG200

  • BC4J View not Thread safe, user sessions are using the same view instance

    Hi There,
    We are using BC4J that came with JDeveloper 10.1.2.0.0 with Oracle 10G 10.1.2.0.0.
    I have an BC4J account search view (BC4J AccountSearchView) that users can call to search for an account. So this view could be used by numerous users and pieces of code at the same time. Now my understanding is that each user gets their own instance of the view so changing the view's query should not be an issue (since the view definition is not changing). Under a light load the account search view looks like everyone get there own instance of the view and there expected account search results. But under a heavy user load when we have User A and User B the search query that was for User A will be used by User B. So the user results for one user will get the other users results.
    I do not understand if the view definition is been changed by the other user and is impacting all view instances. How can this occur if it is thread safe?
    I have enclosed the core code for this search.
    If you can help that would be much appreciated, thanks in advance,
    Nigel
    accountSearchView.setQuery(baseSelectQuery+generateWhereClause());
    logger.debug("SearchAccounts Query: "+accountSearchView.getQuery());
    System.out.println("SearchAccounts SQL: "+accountSearchView.getQuery());
    accountSearchView.setPassivationEnabled(false);
    accountSearchView.setForwardOnly(true);
    accountSearchView.executeQuery();
    get attributes for each row result and place in new Java bean objects and return to user.

    Nigel, we've only certified JDeveloper 10.1.2 against the Struts 1.1 with which it ships.
    If there have been any changes in Struts 1.2 to the Struts Request Processor, then this could easily have an impact on the BC4JRequestProcessor's correct functioning, depending on what the changes were.
    My quick look into the issue tells me that the ActionServlet init parameter named mapping in web.xml that we use for the 9.0.3-style BC4J/Struts integration is getting ignored by Struts 1.2. This parameter is used by Struts 1.1 to globally configure a custom ActionMapping subclass which can support additional properties. My quick test shows me that Struts 1.2 is ignoring this setting and so the oracle.jbo.html.struts11.BC4JActionMapping subclass of Struts's default ActionMapping is not getting used correctly as it does in Struts 1.1. This leads to errors when Struts tries to configure its actions in struts-config.xml since the Apache digester tries to set properties on the ActionMapping instance that don't exist (since the BC4JActionMapping has these properties, and it's not being used).
      <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <init-param>
          <param-name>mapping</param-name>
          <param-value>oracle.jbo.html.struts11.BC4JActionMapping</param-value>
        </init-param>
      </servlet>This is my quick analysis of what's not out-of-the-box compatible. I don't know enough about the changes in Struts 1.2 to know why this Struts 1.1 feature broke in Struts 1.2, or what the Struts 1.2 way to accomplish the same thing is.
    I'd encourage you to use Worldwide Support's Metalink site and open a TAR for any time-critical issues you need assistance in resolving. Many of us are constantly traveling and only able to sporadically chime in with tips in the forum as our time permits.
    The source of the BC4JRequestProcessor ships with the produce in the ./BC4J/src directory inside the bc4jstrutssrc.zip file.

  • Java.util.zip not handling Unicode filenames

    I have a zip file that contains files with Asian filenames. java.util.zip.ZipFile opens it, but the filenames are garbled. Is there any way to handle filenames that contain unicode characters?

    Of course, compression works on bytes, not some higher level constructs like Strings or files.
    You can use the ZipOutputStream or DeflaterOutputStream for compression.
    And the javadoc for Deflater even has a code example of compressing a String.
    Edited by: Kayaman on May 22, 2011 5:04 PM

Maybe you are looking for

  • Unable to see some navigations for one responsibility

    Hello there, We have recently upgraded to OIE.K and Fin_PF.G..after that for one of the responsibility we have some problem with the navigation. General ledger responsibility...uses a menu called GL_SU_SETUP....Under that only...GL_SU_S_ACCOUNT, GL_S

  • Cannot burn or import songs

    Hi everyone, I posted this problem a few days ago, but my question kind of got lost when other peole started posting other questions on the same thread. I still haven't solved my problem, here is the original question: I have my itunes on an external

  • H.264 for HTML5 color shifting in Safari

    Hi, I've got a video that I'm using AME to compress for use as an HTML5 background. The color needs to match exactly so the video can blend into the background. This is proving impossible because the color values are shifting in Safari relative to th

  • Movies previewed in iTunes are resent to AppleTV?

    Hi, just made a strange notice (bug or feature). Playing through some movies here on my mac, are being resynced automatically to my AppleTV. Hmm, the point is, they are already on my AppleTV and get overwritten. I searched with a friend through a cou

  • Upgrading in Firefox cost me ALL MY BOOKMARKS AND my YAHOO e-mail. Why?

    For the second time in a month, I "upgraded" because of a Firefox suggestion that kept popping up on my screen to do so. Now, for the second time, ALL MY BOOKMARKS are GONE, and, when I try to bring up my Yahoo e-mail account, all I get is a bar the