JDK 1.4.2 Collections.unmodifiableMap() thread safe?

Hello,
doesn anyone know if the call to Collections.unmodifiableMap() is thread safe.
Thanks
Marc

What do you mean?
The Collections.unmodifiableMap() doesn't modify anything so in one sense it is thread safe, however it doesn't guarentee you won't modify the underlying map in anothe thread so it won't stop you from doing unthread safe behaviour.

Similar Messages

  • Thread-safe design pattern for encapsulating Collections?

    Hi,
    This must be a common problem, but I just can't get my head around it.
    Bascially I'm reading in data from a process, and creating/updating data structuers from this data. I've got a whloe bunch of APTProperty objects (each with a name/value) stored in a sychronized HashMap encapsulated by a class called APTProperties. It has methods such as:
    addProperty(APTProperty) // puts to hashmap
    getProperty(String name) // retreives from hashmap
    I also want clients to be able to iterate through all the APTProperties, in a thread safe manner . ie. they aren't responsible for sychronizing on the Map before getting the iterator. (See Collections.synchronizedMap() API docs).
    Is there any way of doing this?
    Or should I just have a method called
    Iterator propertyIterator() which returns the corresponding iterator of the HashMap (but then I can't really make it thread safe).
    I'd rather not make the internal HashMap visible to calling clients, if possible, 'cause I don't want people tinkering with it, if you know what I mean.
    Hope this makes sense.
    Keith

    In that case, I think you need to provide your own locking mechanism.
    public class APTProperties {
    the add, get and remove methods call lock(), executes its own logic, then call unlock()
    //your locking mechanism
    private Thread owner; //dont need to be volatile due to synchronized access
    public synchronized void lock() {
    while(owner != null) {
    wait();
    th = Thread.currentThread();
    public synzhronized void unlock() {
    if(owner == currentThread()){
    owner = null;
    notifyAll();
    }else {
    throw new IllegalMonitorStateException("Thread: "+ Thread.currentThread() + "does not own the lock");
    Now you dont gain a lot from this code, since a client has to use it as
    objAPTProperties.lock();
    Iterator ite = objAPTProperties.propertyIterator();
    ... do whatever needed
    objAPTProperties.unlock();
    But if you know how the iterator will be used, you can make the client unaware of the locking mechanism. Lets say, your clients will always go upto the end thru the iterator. In that case, you can use a decorator iterator to handle the locking
    public class APTProperties {
    public Iterator getThreadSafePropertyIterator() {
    private class ThreadSafeIterator implements Iterator {
    private iterator itr;
    private boolean locked;
    private boolean doneIterating;
    public ThreadSafeIterator(Iterator itr){
    this.itr = itr;
    public boolean hasNext() {
    return doneIterating ? false : itr.hasNext();
    public Object next() {
    lockAsNecessary();
    Object obj = itr.next();
    unlockAsNecessary();
    return obj;
    public void remove() {
    lockAsNecessary();
    itr.remove();
    unlockAsNecessary();
    private void lockAsNecessary() {
    if(!locked) {
    lock();
    locked = true;
    private void unlcokAsNecessary() {
    if(!hasNext()) {
    unlock();
    doneIterating = true;
    }//APTProperties ends
    The code is right out of my head, so it may have some logic problem, but the basic idea should work.

  • Is ArrayList(Collection c) constructor  Thread-Safe?

    Hi,
    Say I have the following statement
    public List getList() {
            return new ArrayList(myList);
    }Assuming I also have other methods which use/modify myList, does this method above need to be synchronized?
    Looking into the ArrayList contructor, this eventually calls a static native method System.arraycopy, is this implicitly synchronized as it is native or do I need to take care of this myself?
    Thanks

    The constructor new ArrayList(List) is thread safe because no other thread can access the ArrayList until it because visable to another thread.
    The myList might not be thread safe. i.e. is possible you could be copying the myList while another thread is modifying it? If so then myList should be synchronized.
    Using Vector makes no difference as the list with an issue is myList. Even if myList was a Vector you would have same problem as more than one method is accessed so you would have race condition.
       public ArrayList(Collection c) throws NullPointerException {
            size = c.size();
            // Allow 10% room for growth
            elementData = new Object[
                    (int) Math.min((size * 110L) / 100, Integer.MAX_VALUE)];
            c.toArray(elementData);
        }Note: the c.size() can change between c.size() and c.toArray() being called or while c.toArray() is called. The race condition could mean the collection not being copies or an exception being thrown even if all the methods on the collection are synchronized.
    If you think Vector is so different.
        public Vector(Collection c) throws NullPointerException {
            elementCount = c.size();
            // 10% for growth
            elementData = new Object[
                    (int) Math.min((elementCount * 110L) / 100, Integer.MAX_VALUE)];
            c.toArray(elementData);
        }The only real solution is if myList can be modifed by another thread is to synchronize it and add the following.
    public List getList() {
       synchronized(myList) {
             return new ArrayList(myList);
    }

  • Thread safe Timed Set

    Hello,
    I'm trying to create a thread safe set that also contains a time when it was updated last. It's a cache of a table from the db. I am using CopyOnWriteArraySet as the set is going to be modified rarely, items from set are never modified or removed individually.
    There are couple of questions, is the an existing collection that I can use to achieve the same in JDK 6 (not external libraries)? Is there a better choice over CopyOnWriteArraySet? I tried searching but couldn't find anything.
    If not, would the following implementation suffice my requirements?
    Any suggestions greatly appreciated.
    Thanks in advance,
    -t
    public class CacheSet<T> extends CopyOnWriteArraySet<T> {
    private static final long serialVersionUID = 1L;
    private long lastSyncTime = 0;
    * @param lastSyncTime
    *          the lastSyncTime to set
    public synchronized void setLastSyncTime(long lastSyncTime) {
    this.lastSyncTime = lastSyncTime;
    * @return the lastSyncTime
    public synchronized long getLastSyncTime() {
    return lastSyncTime;
    }

    if you are caching the contents of a table, i assume you are only ever replacing the set. i would suggest something like this:
    public class TableData<T>
      private final Set<T> _tableData;
      private final long _timestamp;
      public TableData(Set<T> data, long timestamp) {
        _tableData = Collections.unmodifiableSet(data);
        _timestamp = timestamp;
      // normal accessors here
    public class TableCache<T>
      private volatile TableData<T> _curTable;
      public void update(TableData<T> newTable)
        _curTable = newTable;
      public TableData<T> get()
        return _curTable;
    }the basic idea is that the TableData class is immutable (e.g. when you update the cache, you create a new set and new TableData instance), so you don't need to worry about concurrency issues (you can pass it a normal HashSet or whatever). thread visibility issues are resolved by using volatile on the TableCache class.
    Edited by: jtahlborn on Apr 17, 2010 10:47 AM

  • Hashtable really thread safe or is there a bug in it ?

    Hashtable is said to be thread-safe, so I think it should be true.
    So I just want someone to tell me what is wrong with my following observation:
    I downloaded the source code of jdk 1.3.1 and read the file Hashtable.java, that contains the implementation code of Hashtables.
    Lots of methods (like get(), put(), contains(), ...) are declared public and synchronized. So far, all is good.
    But the function size() is defined as follows:
    public int size() {
         return count;
    where count is an instance variable defined as follows:
    * The total number of entries in the hash table.
    private transient int count;
    As the function size() is not synchronized, it can retrieve the value of "count" when another method is in the process of updating it.
    For instance, the method put() (that is synchronized) increments the variable "count" with this instruction:
    count++;
    But we know that operation on variable of type "int" are atomic, so this issue doesn't harm the thread safety of the code.
    But there is another issue with multithreading, that deals with caching of data in the working memory of each thread.
    Suppose the following scenario:
    1) Thread A calls method size(). This method reads the value of "count" and put it in the working memory of thread A.
    2) Thread B calls method put(). This method increments "count" using instruction "count++".
    3) Thread A calls method size() again. This method reads the value of "count" from the working memory of the thread, and this cached value may not be the updated value by thread B.
    As size() is not synchronized, or "count" is not declared "volatile", multiple threads may retrieve stale value, because the content of the thread working memory is not in sync with main memory.
    So, here I see a problem.
    Is there something wrong in this observation ?
    But

    Is there something wrong in this observation ?Unfortunately not, as far as I can tell.
    Recent analysis of java's synchronized support has revealed the danger in such unsynchronized code blocks, so it may have been a simple case that it wasn't realised that size is not thread-safe.
    If this is an issue, use Collections.synchronizedMap - in Sun's JDK 1.3, at least, all of the methods are synchronized, except for iterators.
    Regards,
    -Troy

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

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

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

  • SSRS - Is there a multi thread safe way of displaying information from a DataSet in a Report Header?

     In order to dynamically display data in the Report Header based in the current record of the Dataset, we started using Shared Variables, we initially used ReportItems!SomeTextbox.Value, but we noticed that when SomeTextbox was not rendered in the body
    (usually because a comment section grow to occupy most of the page if not more than one page), then the ReportItem printed a blank/null value.
    So, a method was defined in the Code section of the report that would set the value to the shared variable:
    public shared Params as String
    public shared Function SetValues(Param as String ) as String
    Params = Param
    Return Params 
    End Function
    Which would be called in the detail section of the tablix, then in the header a textbox would hold the following expression:
    =Code.Params
    This worked beautifully since, it now didn't mattered that the body section didn't had the SetValues call, the variable persited and the Header displayed the correct value. Our problem now is that when the report is being called in different threads with
    different data, the variable being shared/static gets modified by all the reports being run at the same time. 
    So far I've tried several things:
    - The variables need to be shared, otherwise the value set in the Body can't be seen by the header.
    - Using Hashtables behaves exactly like the ReportItem option.
    - Using a C# DLL with non static variables to take care of this, didn't work because apparently when the DLL is being called by the Body generates a different instance of the DLL than when it's called from the header.
    So is there a way to deal with this issue in a multi thread safe way?
    Thanks in advance!
     

    Hi Angel,
    Per my understanding that you want to dynamic display the group data in the report header, you have set page break based on the group, so when click to the next page, the report hearder will change according to the value in the group, when you are using
    the shared variables you got the multiple thread safe problem, right?
    I have tested on my local environment and can reproduce the issue, according to the multiple safe problem the better way is to use the harshtable behaves in the custom code,  you have mentioned that you have tryied touse the harshtable but finally got
    the same result as using the ReportItem!TextBox.Value, the problem can be cuased by the logic of the code that not works fine.
    Please reference to the custom code below which works fine and can get all the expect value display on every page:
    Shared ht As System.Collections.Hashtable = New System.Collections.Hashtable
    Public Function SetGroupHeader( ByVal group As Object _
    ,ByRef groupName As String _
    ,ByRef userID As String) As String
    Dim key As String = groupName & userID
    If Not group Is Nothing Then
    Dim g As String = CType(group, String)
    If Not (ht.ContainsKey(key)) Then
    ' must be the first pass so set the current group to group
    ht.Add(key, g)
    Else
    If Not (ht(key).Equals(g)) Then
    ht(key) = g
    End If
    End If
    End If
    Return ht(key)
    End Function
    Using this exprssion in the textbox of the reportheader:
    =Code.SetGroupHeader(ReportItems!Language.Value,"GroupName", User!UserID)
    Links belowe about the hashtable and the mutiple threads safe problem for your reference:
    http://stackoverflow.com/questions/2067537/ssrs-code-shared-variables-and-simultaneous-report-execution
    http://sqlserverbiblog.wordpress.com/2011/10/10/using-custom-code-functions-in-reporting-services-reports/
    If you still have any problem, please feel free to ask.
    Regards
    Vicky Liu

  • Thread safe logging class, using final and static

    Hi,
    I'm looking through a logging class (which writes entries to a text file and so on) written by someone else, and I'm trying to determine whether it's thread-safe...
    Essentially the class looks like this:
    public final class Logger {
    private static FileOutputStream fout;
    private static PrinterWriter pout;
    private static final long MaxLength = 100000;
    static {
    /* basically checks size of logfile, if bigger than 100k, then copy it as bak, and start again */
    public void write(String msg) {
    /* write entry into log file */
    public void writeWithTimeStamp(string msg) {
    /* write entry with time stamp into log file */
    Now, I could be wrong, but I don't think that the class is thread-safe is it? in order to be thread-safe, I would have to use synchronized before write() and writeWithTimeStamp(), right?
    My confusion arises from the use of the keyword "final" at the top of the class. This class isn't being inherited (or rather, there's no reason for the class not to be inheritable)... so what is it's purpose, if there is one?!
    And my other question concerns the static block. But I need to describe the current setup first: The Logger class is being use by a file server. File server basically sits there, accepts socket connections from the outside, and takes text files and output them into a local directory. When a new socket connection is created, a new thread is created. As it stands right now, each thread instantiates its own Logger object which seems weird! Bringing me to my question which was, if each thread instantiates its own Logger object, the static block is only ran ONCE, regardless of how many threads (and therefore Logger objects) are created, right??
    And wouldn't it be a better idea to simply create only ONE Logger object and pass it by reference to all newly created threads as they are needed so that all threads access the same and only Logger object? (and therefore utilize sychronization)
    Thanks!

    In JDK 1.4, there are already classes written that do all of that work. Check out the docs for the java.util.logging package. Specifically, check out FileHandler (which can rotate log files if they are greater than a specified size) and LogRecord (which is a standardized way to store logging entries). I believe the class is threadsafe, it doesn't say it isn't. Try it and see. If not, you can easily make a threadsafe wrapper for it (or any class for that matter).
    The online documentation is at:
    http://java.sun.com/j2se/1.4/docs/api/index.html
    If you are curious, the simplest way to make any class threadsafe, if you don't want to or are not able to modify the class code itself is to define another class that calls methods of the original class, but that is synchronized.
    Example:
        // NonThreadSafe.java
        public class NonThreadSafe {
            public NonThreadSafe (String s) {
                // Constructor
            public void SomeMethod (int param) {
                // Do some important stuff here...
            public int AnotherMethod (boolean param) {
                // Do some more important stuff here...
        // ThreadSafeWrapper.java
        public class ThreadSafeWrapper {
            protected NonThreadSafe nts;
            public ThreadSafeWrapper (String s) {
                nts = new NonThreadSafe(s);
            public synchronized void SomeMethod (int param) {
                nts.SomeMethod(param);
            public synchronized int AnotherMethod (boolean param) {
                return nts.AnotherMethod(param);
            public NonThreadSafe GetNonThreadSafe () {
                return nts;
        };Unfortunately, ThreadSafeWrapper isn't derived from NonThreadSafe, so you are somewhat limited in what you can do with it compared to what you could do with NonThreadSafe. AFAIK, you can't override unsynchronized methods with synchronized ones.
    Another thing you could do is just write a method that writes to your logging class, and synchronize just that method. For example:
        // ThreadSafeLogger.java
        public class ThreadSafeLogger {
            public static synchronized void LogMessage (MyLogger log, String msg) {
                log.writeString(msg);
        // In another thread, far, far away:
            ThreadSafeLogger.LogMessage(theLog, "Blah");
            ...Hope that helps.
    Jason Cipriani
    [email protected]
    [email protected]

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

  • Thread Safe Testing

    I havn't written much mult-threaded code but I realise it's important when many web round-trips are required.
    How do I design, test and verify that I have a thread-safe application? I don't like relying on the testing statistics of chance unless the odds of failure are 0.0001%!
    Is there a correct way to verify a thread-safe application?

    I agree it is a lofty, though sadly in all probability too time consuming, goal to achieve. However, there are a few pitfalls to watch out for that should get most of the common, pernicious thread safety issues:
    Synchronize data that must be shared. This will involved performance bottle-necks. If the data is read-mostly, consider a Singleton cache. Though pitfalls will always remain here. Data sharing among threads, IMO, is the single greatest issue.
    Use static methods and instances wisely. If an object has instance variables that are used from method to method call (either within the class or from the caller), then state exists for that object. It is inherently a candidate to look at in terms of thead-safety. This class should be created for each logical unit of work that depends on its state. So, do not reuse these classes among threads (or at least provide an init() or reset() method to clear the state). The same applies to static methods. You can safely use a static method from multiple threads if it does not modify other static variables (e.g., changing the state of a static variable).
    Within the Collections API, pay attention to which types are synchronized and which are not. The Javadocs will specify.
    Try to write methods thread-safe. Have them only use the arguments provided in the method's signature.
    Watch for relatively simple race conditions that can easily be spotted.
    static private Singleton INSTANCE;
    private Singleton() {
        super();
        // Now I will fetch values from a database, perhaps taking seconds
    static final public Singleton getInstance() {
          if (INSTANCE == null) {
             INSTANCE = new Singleton();  // what if this takes some time, e.g. database query to get cache values?
          return INSTANCE;
    }Not good. Here's a possible refactoring:
    private static final Singleton INSTANCE;  // bonus, we can now make it final
    static {
       INSTANCE = new SIngleton();  // Occurs only when class is loaded, atomic
    public static final Singleton getInstance() {
      return INSTANCE;  // no race condition
    }The above would be even more applicable and pronounced if you offered a static refresh() method on the instance, say to refresh its cache of data from a database.
    Seems easy, right? The rub is that you need to verify that a given method does not call other methods that are not thread-safe. If every class you design follows the above precepts, then you will probably only be chasing down rarer thread-safety issues.
    - Saish

  • Is Vector thread-safe in J2ME?

    I understand java.util.Vector is thread-safe in J2SE. How about in Vector in J2ME? I did not find any documentation about this.
    Any help is appreciated.

    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.

  • Is Executor thread-safe

    Hello,
    Suppose you have an Executor to execute tasks (one of the standard implementations provided by the JDK).
    Is there any risk if you have multiple threads that use the executor to submit or execute tasks?.
    In other words: Is Executor thread-safe?
    I'm not talking about the working threads that execute the tasks.
    I'm talking about the threads that send the tasks to execution.
    Thank you.

    JoseLuis wrote:
    can you please tell me where can I find that kind of facts, because I could not find it in the javadoc.Well, it isn't a requirement for ExecutorServices, but it how the implementations provided by the java.util.concurrent package operate. That fact is stated in the API for ThreadPoolExecutor in several places:
    In the class description:
    Queuing
        Any BlockingQueue may be used to transfer and hold submitted tasks.Then, all the Constructors that take work queues only take BlockingQueues, and the getQueue() method returns a BlockingQueue.
    Finally, there are only 2 implementations of the ExecutorService provided, ThreadPoolExecutor, and ScheduledThreadPoolExecutor, which subclasses ExecutorService (and does not indicate different rules for Queues).
    >
    if you can tell me about a book or official document it would be great.
    thanx again

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

  • Is Oracle JDBC driver thread safe

    Is the Oracle JDBC driver thread safe?

    Seems that this is not totally true.
    We have a Problem with Oracle JDBC driver 9.2.0.5.0 (thin)
    Using an IBM JDK 1.4
    Szenario:
    Thread 1 access to a CLOB via
    ResulSet.getCharacterStream(int)
    Thread 2 normal access via some select and
    ResulSet.getString(int)
    (Both using the same connection)
    The following threads appear to be in a circular deadlock.
    Further information can be found by looking in the Overall Thread Analysis
    section of this tool.
    Multi-threaded deadlock 1:
    "Servlet.Engine.Transports : 6" of (sys:0x39778800) (TID:0x104590D0)
    Holding Resource: oracle.jdbc.ttc7.TTC7Protocol@1ADEB358/1ADEB360
    Thread Waiting: "ProcessNotificationTask" (sys:0x3C51FC18) (TID:0x103B4C40)
    "ProcessNotificationTask" of (sys:0x3C51FC18) (TID:0x103B4C40)
    Holding Resource: oracle.jdbc.driver.OracleConnection@1AE45160/1AE45168
    Thread Waiting: "Servlet.Engine.Transports : 6" (sys:0x39778800) (TID:0x104590D0)
    4XESTACKTRACE at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2667)
    4XESTACKTRACE at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2840)
    4XESTACKTRACE at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:608)
    4XESTACKTRACE at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:536)
    4XESTACKTRACE at com.top_logic.knowledge.service.db.DBKnowledgeBase.getObjectsByAttribute(Unknown Source)
    4XESTACKTRACE at oracle.jdbc.ttc7.TTC7Protocol.getLobChunkSize(TTC7Protocol.java:3050)
    4XESTACKTRACE at oracle.sql.LobDBAccessImpl.getChunkSize(LobDBAccessImpl.java:687)
    4XESTACKTRACE at oracle.sql.CLOB.getChunkSize(CLOB.java:692)
    4XESTACKTRACE at oracle.sql.CLOB.getBufferSize(CLOB.java:717)
    4XESTACKTRACE at oracle.sql.CLOB.getCharacterStream(CLOB.java:345)
    4XESTACKTRACE at oracle.sql.CLOB.characterStreamValue(CLOB.java:1377)
    4XESTACKTRACE at oracle.jdbc.driver.OracleStatement.getCharacterStreamValue(OracleStatement.java:5817)
    4XESTACKTRACE at oracle.jdbc.driver.OracleResultSetImpl.getCharacterStream(OracleResultSetImpl.java:1230)
    It seems that the access to the CLOB needs another,
    internal SELECT to the Database and this way
    TTC7Protocol and OracleConnection lock out each other.
    This only happens on a true multiprocessor machine.
    We tried to reprodcue it on a Single Processor
    and some HyperThreading Machine but had no real sucess.
    Now where can I sumbit this as a Bug ?

  • 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

Maybe you are looking for

  • Slow performance while integrating data with ODI while open report

    In ODI i have a schedulled package that runs every 4 hours, this package loads data from an DB table to BAM. Normally each execution loads about 4000 records and takes about 7 seconds to be completed. However, in some executions the same 4000 records

  • Common 3rd Party Jars in an EAR

    Hi I have some common 3rd party jars and zips that are accessed by my WARs and EJB JARs. Where in my EAR structure do i place them so that these common jars like classes12, formulaone etc can be accessed from within my WARs and EJB jars? Regards Sudh

  • Syncing problem HELPPPPP!!!

    Hi, since itunes 7... I've been having issues with podcast syncing... Here is the setting I have with my itunes... 1. podcast setting from itunes... Keep "all unplayed podcast" 2. podcast setting from ipod... sync "all unplayed podcast" so basically

  • File sharing from OS 10.6.5 to host 10.5.8

    I've been trying to connect/fileshare from a macpro (os 10.6.5) to a macpro (os 10.5.8). I keep getting the error "Connection Failed" I can "see" the 10.5.8 computer but cannot connect. However the 10.5.8 can connect just fine to my 10.6.5 file shari

  • Problems Printing from Epson 2400 in Lightroom 2.3

    I'm in the process of switching over from a PC to a Mac. I've gotten lightroom running and transfered all my photos over. But I'm having two big problems printing from my Epson 2400. *8.5x11 prints are offset. The top of the picture starts about an i