The get() of Vector class, is it thread safe??

Hi all:
the get() of Vector class, is it thread safe?? I looked into the API, but no info is available, so any help is appreciated

You just have to look out when you perform two or more methods on the Vector in sucession. Then it's better to lock on the vector itself. If you for instance access the vector to query whether the size is greater than zero and immediately remove an item while another thread is removing elements from the same vector, you might get a dirty read and call get() on the vector while there are no elements left.

Similar Messages

  • Vector is not  a Thread safe so where be use it and why?

    Can anyone tell me
    When Vector is not a Thread safe so where be use it and why?

    Suppose you use a Vector<Listener> to store your list of listeners. While the Vector class is thread-safe, which means that its methods can be called without additional synchronization without risk of corrupting the Vector data structures, iterating a collection involves "check-then-act" sequences, which are at risk of failing if the collection is modified during iteration. Let's say there are three listeners in your list at the start of iteration. As you iterate through the Vector, you repeatedly call size() and get() until there are no more elements to retrieve, as in Listing 1:
    Listing 1. Unsafe iteration of a Vector
    Vector<Listener> v;
    for (int i=0; i<v.size(); i++)
    v.get(i).eventHappened(event);
    But what happens if, just after you call Vector.size() for the last time, someone removes a listener from the list? Now, Vector.get() will return null (which is correct, because the state of the vector has changed since you last checked), and you will throw a NullPointerException when you try to call eventHappened(). This is an example of a check-then-act sequence -- you check to see if any more elements exist, and if so, you get the next element -- but in the presence of concurrent modification, the state could have changed since the check.
    I read that at IBM sites
    Thanks in advance for clearing my doubts...

  • 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

  • Help! how to refresh the JTable of a class from another thread class

    there is an application, in server side ,there are two classes, one is a class called face class that screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much

    thank you very much !
    i tried it ,but the TableModel i used like this ,and how to change the TableModel?
    here the files of mine ,pls give me some help,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write?? }
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

  • About the thread safe variable

    Hello,
    I have make 2 projects, the first is using to initialize the enviroument an  loading  some modules, and the 2nd using to execute a special work. In the first project, I use the DeclareThreadSafeScalarVar macro to define the handle of a file, I think the file handle can be shared between 2 processes, and each process can access data by the file handle.It is worth mentioning that the 2nd process loading is by the CreateProcess() API. My question is : if the safe variable is initialized in the first process, can I use the safe variable in the second process? Do I need to reinitialize the safe variable in the 2nd process? Thanks.
    David

    David,
    Thread safe variables are only going to work for threads within the same process. Windows does not allow you to access memory outside of the virtual space of your application. Thus the processes act as if they are unaware of each other's data. Even if you send a pointer to the other application, it will not be able to access the data. There are a few other options for interapplication communication.
    1. When you are calling CreateProcess() you can pass the new process some command line arguments. If the data you want to send can be serialized, then you can pass it to the other application at start using this command.
    2. You can pass the data using WM_COPYDATA which allows you to set up a special structure and send it to the other application. This is similar to what you wanted to do with the thread safe variables, except that this data will be read only and must be sent to the other process using something like SendMessage(). This gets quite a bit more complicated.
    3. You can set up a client server architecture and have all of the data management handled by the server process.
    From what you have said about your application so far, it may be simpler to just create a single process with two threads. If the applications are dependent on each other, then they likely need to be part of the same process.
    National Instruments
    Product Support Engineer

  • SwingWorker process(List V chunks) but List isn't thread safe is it.

    Folks,
    Am I missing something or does
    protected void process(List<V> chunks)in the new 1.6 javax.swing.SwingWorker represent a potential threading issue?
    List isn't thread safe... so why not use a Vector, which is? Except that Vector is currently considered persona-non-grata by bigger brains than me.
    Hmmm... Of course, I don't know which implementation of List is being used under the hood, so I suppose I just have to trust the Java Gods who built the new SwingWorker to have used a thread safe implementation... which is pretty good bet, I suppose...
    Can anyone state categorically that it isn't a problem?
    Thanx. Keith.
    Message was edited by: corlettk PS: I'm knee deep in thread gruel and going down fast.

    publish definitely does not block until process is finished.
    In fact calling publish does not necessarily mean that process will be called right away.
    From the API:
    Because the process method is invoked asynchronously on the Event Dispatch Thread multiple invocations to the publish method might occur before the process method is executed. For performance purposes all these invocations are coalesced into one invocation with concatenated arguments.
    For example:
    publish("1");
    publish("2", "3");
    publish("4", "5", "6");
    might result in:
    process("1", "2", "3", "4", "5", "6")
    Edit:
    The only source I could find for AccumulativeRunnable (the class used to accumulate the arguments passed to publish) was here:
    http://fisheye5.cenqua.com/browse/swingworker/src/java/org/jdesktop/swingworker/AccumulativeRunnable.java?r=1.2
    which isn't necessarily the implementation in the JDK but it's probably close.
    That shows that before process is called the accumulating list reference is nulled, meaning that there is no way that publish can append to the list during a call to process.
    In fact calling publish as the same time as process is executing on the EDT appends the published arguments to a fresh list, leading to another call to process at some later time (in SwingWorker the delay between a call to publish and a call to process is at most 1000/30 milliseconds).
    Message was edited by:
    dwg

  • 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

  • Is addBatch/executeBatch thread safe

    Hi,
    I want to make a prepared statement that is shared between two threads.
    one thread will perform the addBatch and the other thread will periodically executeBatch.
    will this work safely or it will cause problems with concurrency?

    I tried to use queuing using a Vector but in time the
    queue gets bigger, and eventually gives out of
    memory, also causes delay on insertion of data.Batch will suffer from all the same problems as well as some others. Where do you think the data in the batch is stored prior to transmission?
    Please don't take this the wrong way, but I don't think you're competent to do this. Use a single threaded approach.
    I already tried to use the approach I am asking about
    in the first post, it works fine without delay or
    memory issuesYou merely implemented the vector approach incorrectly. Or possibly you weren't correctly batching your transmissions.
    , But I am still not sure if a
    concurrency issue will rise in the future.It will.
    so are they thread safe or not?Nothing to do with JDBC is threadsafe except for acquisition of a connection. It's your responsibility to ensure thread safety, and I don't believe you're likely to get this right if you weren't aware of that in the first place.
    It sounds like an insult, I know, but it's not something anyone is born knowing.

  • Is XMLProcessor Thread Safe?

    I was wondering if the XMLProcessor.processXSL(xsl, null) method is thread safe?
    What if there were a single instance ( Singleton ), would it be able to handle multiple request without failing?
    Any help or direction would be of great help.
    null

    is vector thread safe ?
    is arraylist thread safe ?
    i want to use any one of thsese without
    Synchronised keyword
    Vector is synchronized but ArrayList is not. This means that two different threads cannot access the same method in a Vector at the same time. An ArrayList can easily be made synchronized and will then behave as a Vector.
    Now synchronized methods don't necessarily lead to thread-safe code. That depends on how the Vector/ArrayList is used. Have a look at the new concurrency package in Java 5. It contains lots of readymade collections with different behaviours. Maybe one will suit your needs and be thread-safe with your usage right out of the box.

  • [SOLVED] Singleton thread safe

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

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

  • What is "Thread Safe"?

    I have heard a lot of folks talking about a class that is "Thread Safe".
    I am assuming that this means the obect can be accessed by more than one thread at a time. I do not know what the concept really means in practice.
    My question is, how can I tell if something is thread safe, what do I need to look out for?

    Basically you're looking to avoid unwanted behavior by simultaneous access. Here are a couple examples I've seen:
    Assuming myID is a class variable...
    public void assignID(Client currentClient) {
    myID = (some new random value)
    currentClient.ID = myID;
    In the above example, what happens if two threads access the method at the same time? The first one starts, assigning a value to the myID variable. Then the second one starts, assigning a value to myID AGAIN. Then when both clients assign their currentClients, they'll both end up with the same ID. To avoid a code block being accessed by two clients simultaneously, use the "synchronized" keyword.
    Here's another one. Assume you have a Hashtable:
    Enumerator myEnum = myHashtable.keys()
    while (myEnum.hasMoreElements()) {
    Object myKey = myEnum.nextElement();
    myHashtable.remove(myKey);
    This should not work in Java (and I know it doesn't in C# which I'm currrently being forced to use at work) because you're iterating through the keys of a Hashtable. But while you're trying to go linearly from key to key, you're also removing elements of the Hashtable. You're trying to operate on the object twice and the object doesn't allow it.
    There are a couple ideas. I wrote a database pool once and had to synchronize methods so two clients didn't try to execute a query through the same Connection, etc.
    Michael Bishop

  • 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,
    Reggie

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

  • What does it mean to be "thread safe"?

    What does it mean to be "thread safe"?
    I am working with a team on a project here at work. Someone here suggested that we build all of our screens during the initialization of the application to save time later. During the use of the application, the screens would then be made visible or invisible.
    One of the objections to that idea was that the swing components (many of which we use) are not thread safe. Can anyone tell me what the relevance of that is?
    Thanks

    To understand why Swing is not thread safe you have to understand a little bit of history, and a little bit of how swing actually works. The history(short version) is that it is nearly impossible to make a GUI toolkit thread safe. X is thread safe(well, sorta) and it's a really big mess. So to keep things simple(and fast) Swing was developed with an event model. The swing components themselves are not thread safe, but if you always change them with an event on the event queue, you will never have a problem. Basically, there is a Thread always running with any GUI program. It's called the awt event handler. When ever an event happens, it goes on an event queue and the event handler picks them off one by one and tells the correct components about it. If you have code that you want to manipulate swing components, and you are not ON the awt thread(inside a listener trail) you must use this code.
    SwingUtilities.invokeLater( new Runnable() {
      public void run() {
        // code to manipulate swing component here
    });This method puts the defined runnable object on the event queue for the awt thread to deal with. This way changes to the components happen in order, in a thread safe way.

  • Is TelemetryClient thread-safe?

    The only tutorial for client events I found is down at the moment (404):
    http://azure.microsoft.com/en-us/documentation/articles/app-insights-web-track-usage-custom-events-metrics
    However looking at the cached version, it doesn't mention threading concerns.
    The docs say its methods are not thread safe but I'm wondering if that's just the boilerplate template. If it really isn't thread safe, what
    is the recommended practice in a multi-threaded environment? lock around each call? instantiate a new client for each call? synchronize calls in a queue?
    Thanks,
    Ohad

    Hi Oleg, thanks for clarifying that.
    Perhaps you could modify the docs to point that out.
    I'm confused though, why pay the overhead of thread-safety if you recommend creating a new instance every time?
    BTW I don't know if it was your doing, but the
    article is back online :)

  • Are SocketFactory implementations thread-safe?

    Hi!
    I'm using a SSLSocketFactory-singleton (SSLSocketFactoryImpl it is I guess) for creating SSLSocket-instances in my application.
    I just wondered whether or not I need synchronization especially for using the createSocket(...)-methods in my multi-threaded application, since I can't look in the code due to restrictions. Another question is whether the answer applies to other SocketFactory implementations.
    Greetings

    georgemc wrote:
    JAVAnetic wrote:
    georgemc wrote:
    Why would you need SocketFactory to be thread-safe anyway?Because, in my multi-threaded application I want to use only one SocketFactory-instance to reduce the overhead of creating one per thread that needs Sockets. So this instance as a shared object used by many threads will need to be synchronized if it is not already thread-safe per se. But all you do with a SocketFactory is ask it for sockets. What issues do you think you'll face with multi-threaded requests for new instances of something? Just because you've got multi-threaded code, doesn't mean everything you use has to be synchronized.I know, but since I don't know what the factory-implementation actually does creating those instances I think it is always worth asking, if I have to synchronize even if it may be true that the design of (the) factory-implementation(s) is in fact thread-safe, which no one until now could tell me for sure.

Maybe you are looking for

  • Looking for a proven CRM app.

    I am a field sales representative and I am looking for a program which will help me to manage my potential customers and existing customers in the same place. I have had a look in the app store and there are many there (potentially), but the feed bac

  • Can I use an external SSD drive as main drive?

    I would like to use an external SSD drive as my boot/operating drive.  Basically a clone of my current HD but have the option of booting to and using the external SSD drive for system and apps and data.  Is it possible and if so how?

  • Part Number for parallel cable connecting SCXI-2400 to SCXI-1200

    If no longer available from NI, would anyone have the (upper) rear connector pinout for the SCXI-2400 so I can make my own cable using half of a DB-25 parallel printer cable and the appropriate AMP connector?

  • Execute Excel Macro Through DIAdem

    Hi All,   I am currently trying to run a script in DIAdem which exports certain material properties to an Excel Macro-enabled workbook.  Inside the Excel workbook the user executes a macro to perform some calculations.  The results of that calculatio

  • When does a mountet network drive goes from green to red in colour due to low disk space?

    Hi, I have a number of network shares on MS 2008 R2 servers, that my users have mountet on their Win7 PC's. What is the limit for when a mountet network drive goes from green to red on the users PC, due to low disk space. My guess is below 10% but I