Search Results

Search found 655 results on 27 pages for 'synchronized'.

Page 2/27 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Java Concurrency : Synchronized(this) => and this.wait() and this.notify()

    - by jens
    Hello Experts, I would appreciate your help in understand a "Concurrency Example" from: http://forums.sun.com/thread.jspa?threadID=735386 Qute Start: public synchronized void enqueue(T obj) { // do addition to internal list and then... this.notify(); } public synchronized T dequeue() { while (this.size()==0) { this.wait(); } return // something from the queue } Quote End: My Question is: Why is this code valid? = When I synchronize a method like "public synchronized" = then I synchronize on the "Instance of the Object == this". However in the example above: Calling "dequeue" I will get the "lock/monitor" on this Now I am in the dequeue method. As the list is zero, the calling thread will be "waited" From my understanding I have now a deadlock situation, as I will have no chance of ever enquing an object (from an nother thread), as the "dequeue" method is not yet finised and the dequeue "method" holds the lock on this: So I will never ever get the possibility to call "enequeue" as I will not get the "this" lock. Backround: I have exactly the same problem: I have some kind of connection pool (List of Connections) and need to block if all connections are checked. What is the correct way to synchronize the List to block, if size exceeds a limit or is zero? Thank you very much Jens

    Read the article

  • Is nested synchronized block necessary?

    - by Dan
    I am writing a multithreaded program and I have a method that has a nested synchronized blocks and I was wondering if I need the inner sync or if just the outer sync is good enough. public class Tester { private BlockingQueue<Ticket> q = new LinkedBlockingQueue<>(); private ArrayList<Long> list = new ArrayList<>(); public void acceptTicket(Ticket p) { try { synchronized (q) { q.put(p); synchronized (list) { if (list.size() < 5) { list.add(p.getSize()); } else { list.remove(0); list.add(p.getSize()); } } } } catch (InterruptedException ex) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); } } } EDIT: This isn't a complete class as I am still working on it. But essentially I am trying to emulate a ticket machine. The ticket machine maintains a list of tickets in the BlockingQueue q. Whenever a client adds a ticket to the machine, the machine also keeps track of the price of the last 5 tickets (ArrayList list)

    Read the article

  • Writing a synchronized thread-safety wrapper for NavigableMap

    - by polygenelubricants
    java.util.Collections currently provide the following utility methods for creating synchronized wrapper for various collection interfaces: synchronizedCollection(Collection<T> c) synchronizedList(List<T> list) synchronizedMap(Map<K,V> m) synchronizedSet(Set<T> s) synchronizedSortedMap(SortedMap<K,V> m) synchronizedSortedSet(SortedSet<T> s) Analogously, it also has 6 unmodifiedXXX overloads. The glaring omission here are the utility methods for NavigableMap<K,V>. It's true that it extends SortedMap, but so does SortedSet extends Set, and Set extends Collection, and Collections have dedicated utility methods for SortedSet and Set. Presumably NavigableMap is a useful abstraction, or else it wouldn't have been there in the first place, and yet there are no utility methods for it. So the questions are: Is there a specific reason why Collections doesn't provide utility methods for NavigableMap? How would you write your own synchronized wrapper for NavigableMap? Glancing at the source code for OpenJDK version of Collections.java seems to suggest that this is just a "mechanical" process Is it true that in general you can add synchronized thread-safetiness feature like this? If it's such a mechanical process, can it be automated? (Eclipse plug-in, etc) Is this code repetition necessary, or could it have been avoided by a different OOP design pattern?

    Read the article

  • What is wrong with my @synchronized block?

    - by hyn
    I have 2 threads in my application, a game update thread and render/IO/main thread. My update thread updates the game state, and the render thread renders the scene based on the updated values of the game state models and a few other variables stored inside an object (gameEngine). The render thread gets executed while the game thread is still updating, which is a problem, so it appeared to me the solution is to use @synchronized like this: @synchronized(gameEngine) { [gameEngine update]; nextUpdate = now + GAME_UPDATE_INTERVAL; gameEngine.lastGameUpdateInterval = now - lastUpdate; gameEngine.lastGameUpdateTime = now; lastUpdate = now; } But the render thread still accesses the gameEngine object between -update and the last 3 lines of the block. Why is this?

    Read the article

  • Preventing multiple repeat selection of synchronized Controls ?

    - by BillW
    The working code sample here synchronizes (single) selection in a TreeView, ListView, and ComboBox via the use of lambda expressions in a dictionary where the Key in the dictionary is a Control, and the Value of each Key is an Action<int. Where I am stuck is that I am getting multiple repetitions of execution of the code that sets the selection in the various controls in a way that's unexpected : it's not recursing : there's no StackOverFlow error happening; but, I would like to figure out why the current strategy for preventing multiple selection of the same controls is not working. Perhaps the real problem here is distinguishing between a selection update triggered by the end-user and a selection update triggered by the code that synchronizes the other controls ? Note: I've been experimenting with using Delegates, and forms of Delegates like Action<T>, to insert executable code in Dictionaries : I "learn best" by posing programming "challenges" to myself, and implementing them, as well as studying, at the same time, the "golden words" of luminaries like Skeet, McDonald, Liberty, Troelsen, Sells, Richter. Note: Appended to this question/code, for "deep background," is a statement of how I used to do things in pre C#3.0 days where it seemed like I did need to use explicit measures to prevent recursion when synchronizing selection. Code : Assume a WinForms standard TreeView, ListView, ComboBox, all with the same identical set of entries (i.e., the TreeView has only root nodes; the ListView, in Details View, has one Column). private Dictionary<Control, Action<int>> ControlToAction = new Dictionary<Control, Action<int>>(); private void Form1_Load(object sender, EventArgs e) { // add the Controls to be synchronized to the Dictionary // with appropriate Action<int> lambda expressions ControlToAction.Add(treeView1, (i => { treeView1.SelectedNode = treeView1.Nodes[i]; })); ControlToAction.Add(listView1, (i => { listView1.Items[i].Selected = true; })); ControlToAction.Add(comboBox1, (i => { comboBox1.SelectedIndex = i; })); } private void synchronizeSelection(int i, Control currentControl) { foreach(Control theControl in ControlToAction.Keys) { // skip the 'current control' if (theControl == currentControl) continue; // for debugging only Console.WriteLine(theControl.Name + " synchronized"); // execute the Action<int> associated with the Control ControlToAction[theControl](i); } } private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { synchronizeSelection(e.Node.Index, treeView1); } private void listView1_SelectedIndexChanged(object sender, EventArgs e) { // weed out ListView SelectedIndexChanged firing // with SelectedIndices having a Count of #0 if (listView1.SelectedIndices.Count > 0) { synchronizeSelection(listView1.SelectedIndices[0], listView1); } } private void comboBox1_SelectedValueChanged(object sender, EventArgs e) { if (comboBox1.SelectedIndex > -1) { synchronizeSelection(comboBox1.SelectedIndex, comboBox1); } } background : pre C# 3.0 Seems like, back in pre C# 3.0 days, I was always using a boolean flag to prevent recursion when multiple controls were updated. For example, I'd typically have code like this for synchronizing a TreeView and ListView : assuming each Item in the ListView was synchronized with a root-level node of the TreeView via a common index : // assume ListView is in 'Details View,' has a single column, // MultiSelect = false // FullRowSelect = true // HideSelection = false; // assume TreeView // HideSelection = false // FullRowSelect = true // form scoped variable private bool dontRecurse = false; private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { if(dontRecurse) return; dontRecurse = true; listView1.Items[e.Node.Index].Selected = true; dontRecurse = false; } private void listView1_SelectedIndexChanged(object sender, EventArgs e) { if(dontRecurse) return // weed out ListView SelectedIndexChanged firing // with SelectedIndices having a Count of #0 if (listView1.SelectedIndices.Count > 0) { dontRecurse = true; treeView1.SelectedNode = treeView1.Nodes[listView1.SelectedIndices[0]]; dontRecurse = false; } } Then it seems, somewhere around FrameWork 3~3.5, I could get rid of the code to suppress recursion, and there was was no recursion (at least not when synchronizing a TreeView and a ListView). By that time it had become a "habit" to use a boolean flag to prevent recursion, and that may have had to do with using a certain third party control.

    Read the article

  • Java Synchronized List Deadlock

    - by portoalet
    From Effective Java 2nd edition item 67 page 266-268: The background thread calls s.removeObserver, which attempts to lock observers, but it can’t acquire the lock, because the main thread already has the lock. All the while, the main thread is waiting for the background thread to finish removing the observer, which explains the deadlock. I am trying to find out which threads deadlock in the main method by using ThreadMXBean (http://stackoverflow.com/questions/1102359/programmatic-deadlock-detection-in-java) , but why does it not return the deadlocked threads? I used a new Thread to run the ThreadMXBean detection. public class ObservableSet<E> extends ForwardingSet<E> { public ObservableSet(Set<E> set) { super(set); } private final List<SetObserver<E>> observers = new ArrayList<SetObserver<E>>(); public void addObserver(SetObserver<E> observer) { synchronized(observers) { observers.add(observer); } } public boolean removeObserver(SetObserver<E> observer) { synchronized(observers) { return observers.remove(observer); } } private void notifyElementAdded(E element) { synchronized(observers) { for (SetObserver<E> observer : observers) observer.added(this, element); } } @Override public boolean add(E element) { boolean added = super.add(element); if (added) notifyElementAdded(element); return added; } @Override public boolean addAll(Collection<? extends E> c) { boolean result = false; for (E element : c) result|=add(element); //callsnotifyElementAdded return result; } public static void main(String[] args) { ObservableSet<Integer> set = new ObservableSet<Integer>(new HashSet<Integer>()); final ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); Thread t = new Thread(new Runnable() { @Override public void run() { while( true ) { long [] threadIds = threadMxBean.findDeadlockedThreads(); if( threadIds != null) { ThreadInfo[] infos = threadMxBean.getThreadInfo(threadIds); for( ThreadInfo threadInfo : infos) { StackTraceElement[] stacks = threadInfo.getStackTrace(); for( StackTraceElement stack : stacks ) { System.out.println(stack.toString()); } } } try { System.out.println("Sleeping.."); TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); t.start(); set.addObserver(new SetObserver<Integer>() { public void added(ObservableSet<Integer> s, Integer e) { ExecutorService executor = Executors.newSingleThreadExecutor(); final SetObserver<Integer> observer = this; try { executor.submit(new Runnable() { public void run() { s.removeObserver(observer); } }).get(); } catch (ExecutionException ex) { throw new AssertionError(ex.getCause()); } catch (InterruptedException ex) { throw new AssertionError(ex.getCause()); } finally { executor.shutdown(); } } }); for (int i = 0; i < 100; i++) set.add(i); } } public interface SetObserver<E> { // Invoked when an element is added to the observable set void added(ObservableSet<E> set, E element); } // ForwardingSet<E> simply wraps another Set and forwards all operations to it.

    Read the article

  • Decentralized synchronized secure data storage

    - by Alberich
    Introduction Hi, I am going to ask a question which seems utopic for me, but I need to know if there is a way to achieve what I need. And if not, I need to know why not. The idea Suppose I have a database structure, in MySql. I want to create some solution to allow anyone (no matter who, no matter where) to have a synchronized copy (updated clone) of this database (with its content) Well, and it is not going to be just one synchronized copy, it could (and should) be a multiple replication (supposing the basic, this means, for example, ten copies all over the world) And, the most important thing: It must be secure. By secure I mean only real-accepted transactions will be synchronized with all the others (no matter how many) database copies/clones. Note: Since it would be quite difficult to make the synchronization in real-time, I will design everything to make this feature dispensable. So it is not required. My auto-suggestion This is how I am thinking to manage it: Time identifiers and Updates checking: Every action (insert, update, delete...) will be stored as the action instruction itself, associated to the time identifier. [I think better than a DATETIME field, it'll be an INT one, with the number of miliseconds passed from 1st january 2013 on, for example]. So each copy is going to ask to the "neighbour copy" for new actions done since last update, and execute them after checking they are allowed. Problem 1: the "neighbour copy" could be outdated too. Solution 1: do not ask just one neighbour, create a random list with some of the copies/clones and ask them for news (I could avoid the list and ask ALL the clones for updates, but this will be inefficient if clones number ascends too much). Problem 2: Real-time global synchronization is not active. What if... Someone at CLONE_ENTERPRISING inserts a row into TABLE. ... this row goes to every clone ... Someone at CLONE_FIXEMALL deletes this row. ... and at the same time, somewhere in an outdated clone ... Someone at CLONE_DROPOUT edits this row (now inexistent at the other clones) Solution 2: easy stuff, force a GLOBAL synchronization before doing any new "depending-on-third-data action" (edit, for example). This global synch. will be unnecessary when making an INSERT, for instance. Note: Well, someone could have some fun, and make the same insert in two clones... since they're not getting updated in real-time, this row will exist twice. But, it's the same as when we have one single database, in some needed cases we check if there is an existing same-row before doing the final action. Not a problem. Problem 3: It is possible to edit the code and do not filter actions, so someone could spread instructions to delete everything, or just make some trolling activity. This is not a problem, since good clones will always be somewhere. Those who got bad won't interest anymore. I really appreciate if you read. I know this is not the perfect solution, it has possibly hundred of holes, but it is my basic start. I will now appreciate anything you can teach me now. Thanks a lot. PS.: It could be that all this I am trying already exists and has its own name. Sorry for asking then (I'd anyway thank this name, if it exists)

    Read the article

  • Can a thread call wait() on two locks at once in Java (6)

    - by Dr. Monkey
    I've just been messing around with threads in Java to get my head around them (it seems like the best way to do so) and now understand what's going on with synchronize, wait() and notify(). I'm curious about whether there's a way to wait() on two resources at once. I think the following won't quite do what I'm thinking of: synchronized(token1) { synchronized(token2) { token1.wait(); token2.wait(); //won't run until token1 is returned System.out.println("I got both tokens back"); } } In this (very contrived) case token2 will be held until token1 is returned, then token1 will be held until token2 is returned. The goal is to release both token1 and token2, then resume when both are available (note that moving the token1.wait() outside the inner synchronized loop is not what I'm getting at). A loop checking whether both are available might be more appropriate to achieve this behaviour (would this be getting near the idea of double-check locking?), but would use up extra resources - I'm not after a definitive solution since this is just to satisfy my curiosity.

    Read the article

  • Synchronized Clipboard?

    - by Boris_yo
    Evernote, Dropbox, Xmarks and what not. Many know these but is there a software that can synchronize clipboard between devices? For what you might be asking? Here is for what: Sometimes I want URL that I see on my desktop/laptop computer to enter into laptop's/smartphone's browser but unless I save that URL to .TXT file, email URL or save to Evernote there is no other way to directly do that. So is there such software already?

    Read the article

  • Postgresql: keep 2 sequences synchronized

    - by Giovanni Di Milia
    Is there a way to keep 2 sequences synchronized in Postgres? I mean if I have: table_A_id_seq = 1 table_B_id_seq = 1 if I execute SELECT nextval('table_A_id_seq'::regclass) I want that table_B_id_seq takes the same value of table_A_id_seq and obviously it must be the same on the other side. I need 2 different sequences because I have to hack some constraints I have in Django (and that I cannot solve there).

    Read the article

  • @synchronized doesn't work in static library

    - by David Beck
    For some reason, when I try to use @synchronized in a static library for the iPhone, I get an error in the project that uses it: Undefined symbols: "___restore_vfp_d8_d15_regs", referenced from: -[GVInbox addConversation:] in libGVKit.a(GVInbox.o) "___save_vfp_d8_d15_regs", referenced from: -[GVInbox addConversation:] in libGVKit.a(GVInbox.o) ld: symbol(s) not found collect2: ld returned 1 exit status

    Read the article

  • Java Synchronized function

    - by leon
    Hi I have a question. In the following code, if a thread were blocked at wait statement, and another thread attempts to execute foo(), would the hello wolrd message be printed? and Why? Many Thanks synchronized foo(){ system.out.println("hello world"); ..... wait(); ..... }

    Read the article

  • How to unit test synchronized code

    - by gillJ
    Hi, I am new to Java and junit. I have the following peice of code that I want to test. Would appreciate if you could send your ideas about what's the best way to go about testing it. Basically, the following code is about electing a leader form a Cluster. The leader holds a lock on the shared cache and services of the leader get resumed and disposed if it somehow looses the lock on the cache. How can i make sure that a leader/thread still holds the lock on the cache and that another thread cannot get its services resumed while the first is in execution? public interface ContinuousService { public void resume(); public void pause(); } public abstract class ClusterServiceManager { private volatile boolean leader = false; private volatile boolean electable = true; private List<ContinuousService> services; protected synchronized void onElected() { if (!leader) { for (ContinuousService service : services) { service.resume(); } leader = true; } } protected synchronized void onDeposed() { if (leader) { for (ContinuousService service : services) { service.pause(); } leader = false; } } public void setServices(List<ContinuousService> services) { this.services = services; } @ManagedAttribute public boolean isElectable() { return electable; } @ManagedAttribute public boolean isLeader() { return leader; } public class TangosolLeaderElector extends ClusterServiceManager implements Runnable { private static final Logger log = LoggerFactory.getLogger(TangosolLeaderElector.class); private String election; private long electionWaitTime= 5000L; private NamedCache cache; public void start() { log.info("Starting LeaderElector ({})",election); Thread t = new Thread(this, "LeaderElector ("+election+")"); t.setDaemon(true); t.start(); } public void run() { // Give the connection a chance to start itself up try { Thread.sleep(1000); } catch (InterruptedException e) {} boolean wasElectable = !isElectable(); while (true) { if (isElectable()) { if (!wasElectable) { log.info("Leadership requested on election: {}",election); wasElectable = isElectable(); } boolean elected = false; try { // Try and get the lock on the LeaderElectorCache for the current election if (!cache.lock(election, electionWaitTime)) { // We didn't get the lock. cycle round again. // This code to ensure we check the electable flag every now & then continue; } elected = true; log.info("Leadership taken on election: {}",election); onElected(); // Wait here until the services fail in some way. while (true) { try { Thread.sleep(electionWaitTime); } catch (InterruptedException e) {} if (!cache.lock(election, 0)) { log.warn("Cache lock no longer held for election: {}", election); break; } else if (!isElectable()) { log.warn("Node is no longer electable for election: {}", election); break; } // We're fine - loop round and go back to sleep. } } catch (Exception e) { if (log.isErrorEnabled()) { log.error("Leadership election " + election + " failed (try bfmq logs for details)", e); } } finally { if (elected) { cache.unlock(election); log.info("Leadership resigned on election: {}",election); onDeposed(); } // On deposition, do not try and get re-elected for at least the standard wait time. try { Thread.sleep(electionWaitTime); } catch (InterruptedException e) {} } } else { // Not electable - wait a bit and check again. if (wasElectable) { log.info("Leadership NOT requested on election ({}) - node not electable",election); wasElectable = isElectable(); } try { Thread.sleep(electionWaitTime); } catch (InterruptedException e) {} } } } public void setElection(String election) { this.election = election; } @ManagedAttribute public String getElection() { return election; } public void setNamedCache(NamedCache nc) { this.cache = nc; }

    Read the article

  • Class initialization and synchronized class method

    - by nybon
    Hi there, In my application, there is a class like below: public class Client { public synchronized static print() { System.out.println("hello"); } static { doSomething(); // which will take some time to complete } } This class will be used in a multi thread environment, many threads may call the Client.print() method simultaneously. I wonder if there is any chance that thread-1 triggers the class initialization, and before the class initialization complete, thread-2 enters into print method and print out the "hello" string? I see this behavior in a production system (64 bit JVM + Windows 2008R2), however, I cannot reproduce this behavior with a simple program in any environments. In Java language spec, section 12.4.1 (http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html), it says: A class or interface type T will be initialized immediately before the first occurrence of any one of the following: T is a class and an instance of T is created. T is a class and a static method declared by T is invoked. A static field declared by T is assigned. A static field declared by T is used and the reference to the field is not a compile-time constant (§15.28). References to compile-time constants must be resolved at compile time to a copy of the compile-time constant value, so uses of such a field never cause initialization. According to this paragraph, the class initialization will take place before the invocation of the static method, however, it is not clear if the class initialization need to be completed before the invocation of the static method. JVM should mandate the completion of class initialization before entering its static method according to my intuition, and some of my experiment supports my guess. However, I did see the opposite behavior in another environment. Can someone shed me some light on this? Any help is appreciated, thanks.

    Read the article

  • Synchronized Enumerator in C#

    - by Dan Bryant
    I'm putting together a custom SynchronizedCollection<T> class so that I can have a synchronized Observable collection for my WPF application. The synchronization is provided via a ReaderWriterLockSlim, which, for the most part, has been easy to apply. The case I'm having trouble with is how to provide thread-safe enumeration of the collection. I've created a custom IEnumerator<T> nested class that looks like this: private class SynchronizedEnumerator : IEnumerator<T> { private SynchronizedCollection<T> _collection; private int _currentIndex; internal SynchronizedEnumerator(SynchronizedCollection<T> collection) { _collection = collection; _collection._lock.EnterReadLock(); _currentIndex = -1; } #region IEnumerator<T> Members public T Current { get; private set;} #endregion #region IDisposable Members public void Dispose() { var collection = _collection; if (collection != null) collection._lock.ExitReadLock(); _collection = null; } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { var collection = _collection; if (collection == null) throw new ObjectDisposedException("SynchronizedEnumerator"); _currentIndex++; if (_currentIndex >= collection.Count) { Current = default(T); return false; } Current = collection[_currentIndex]; return true; } public void Reset() { if (_collection == null) throw new ObjectDisposedException("SynchronizedEnumerator"); _currentIndex = -1; Current = default(T); } #endregion } My concern, however, is that if the Enumerator is not Disposed, the lock will never be released. In most use cases, this is not a problem, as foreach should properly call Dispose. It could be a problem, however, if a consumer retrieves an explicit Enumerator instance. Is my only option to document the class with a caveat implementer reminding the consumer to call Dispose if using the Enumerator explicitly or is there a way to safely release the lock during finalization? I'm thinking not, since the finalizer doesn't even run on the same thread, but I was curious if there other ways to improve this.

    Read the article

  • Synchronized IEnumerator<T>

    - by Dan Bryant
    I'm putting together a custom SynchronizedCollection<T> class so that I can have a synchronized Observable collection for my WPF application. The synchronization is provided via a ReaderWriterLockSlim, which, for the most part, has been easy to apply. The case I'm having trouble with is how to provide thread-safe enumeration of the collection. I've created a custom IEnumerator<T> nested class that looks like this: private class SynchronizedEnumerator : IEnumerator<T> { private SynchronizedCollection<T> _collection; private int _currentIndex; internal SynchronizedEnumerator(SynchronizedCollection<T> collection) { _collection = collection; _collection._lock.EnterReadLock(); _currentIndex = -1; } #region IEnumerator<T> Members public T Current { get; private set;} #endregion #region IDisposable Members public void Dispose() { var collection = _collection; if (collection != null) collection._lock.ExitReadLock(); _collection = null; } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { var collection = _collection; if (collection == null) throw new ObjectDisposedException("SynchronizedEnumerator"); _currentIndex++; if (_currentIndex >= collection.Count) { Current = default(T); return false; } Current = collection[_currentIndex]; return true; } public void Reset() { if (_collection == null) throw new ObjectDisposedException("SynchronizedEnumerator"); _currentIndex = -1; Current = default(T); } #endregion } My concern, however, is that if the Enumerator is not Disposed, the lock will never be released. In most use cases, this is not a problem, as foreach should properly call Dispose. It could be a problem, however, if a consumer retrieves an explicit Enumerator instance. Is my only option to document the class with a caveat implementer reminding the consumer to call Dispose if using the Enumerator explicitly or is there a way to safely release the lock during finalization? I'm thinking not, since the finalizer doesn't even run on the same thread, but I was curious if there other ways to improve this. EDIT After thinking about this a bit and reading the responses (particular thanks to Hans), I've decided this is definitely a bad idea. The biggest issue actually isn't forgetting to Dispose, but rather a leisurely consumer creating deadlock while enumerating. I now only read-lock long enough to get a copy and return the enumerator for the copy.

    Read the article

  • Using Singleton synchronized array with NSThread

    - by hmthur
    I have a books app with a UISearchBar, where the user types any book name and gets search results (from ext API call) below as he types. I am using a singleton variable in my app called retrievedArray which stores all the books. @interface Shared : NSObject { NSMutableArray *books; } @property (nonatomic, retain) NSMutableArray *books; + (id)sharedManager; @end This is accessed in multiple .m files using NSMutableArray *retrievedArray; ...in the header file retrievedArray = [[Shared sharedManager] books]; My question is how do I ensure that the values inside retrievedArray remain synchronized across all the classes. Actually the values inside retrievedArray gets added through an NSXMLParser (i.e. through external web service API). There is a separate XMLParser.m file, where I do all the parsing and fill the array. The parsing is done on a separate thread. - (void) run: (id) param { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL: [self URL]]; [parser setDelegate: self]; [parser parse]; [parser release]; NSString *tmpURLStr = [[self URL]absoluteString]; NSRange range_srch_book = [tmpURLStr rangeOfString:@"v1/books"]; if (range_srch_book.location != NSNotFound) [delegate performSelectorOnMainThread:@selector(parseDidComplete_srch_book) withObject:nil waitUntilDone:YES]; [pool release]; } - (void) parseXMLFile: (NSURL *) url { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self setURL: url]; NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object: nil]; [retrievedArray removeAllObjects]; [myThread start]; [pool release]; } There seems to be some synchronization issues if the user types very quickly (It seems to be working fine if the user types slowly)....So there are 2 views in which the content of an object in this shared array item is displayed; List and Detail. If user types fast and clicks on A in List view, he is shown B in detail view...That is the main issue. I have tried literally all the solutions I could think of, but am still unable to fix the issue. Please suggest some suitable fixes.

    Read the article

  • Highlighting effect to text and/or image similar to be synchronized with audio

    - by Irfan Mulic
    I am looking how to approach following problem: We have application that displays text with audio recorded material. We use Browser Control (Internet Explorer) in Delphi App to do this. We respond to events in Delphi code setting innerHTML for elements if we have to update the style ... Now, request is to add option to dynamically move the cursor or dynamically highlight the words spoken from the paragraph. It doesn't need to match absolutely the exact word spoken so we will have to dynamically update the content of position of highlighted word based on some timer or something (because it is not text to speach). What should be the most practical and easy approach to this kind of problem, all answers are greatly appreciated. Thanks.

    Read the article

  • server controlled or Synchronized web slide show?

    - by Gnome Guru
    I am creating a e-learning application , where the students (wireless) connect to the teachers machine, the teacher hosts a tomcat server. the teacher has a set of HTML web-pages(each of which can be thought of as a slide). and the students can view a web slide-show on his/her browser... the problem is.... i want the pages on the students browser to be redirected according to the teachers input.. in short: i want the server to automatically redirect all the client browsers to the next page when the teacher wants it to be so... how do i do it?? [i am using JSP/javascript/Java/Tomcat/Eclipse]

    Read the article

  • How can I keep a folder synchronized to an external USB hard drive in Ubuntu?

    - by Cesar
    I have a growing music collection which I manually keep in sync with an external USB drive. Sometimes I edit their ID3 tags, add or delete a file in either the hard drive or the USB drive, and I would like to keep those changes synchronized between both. Does Ubuntu has something available that would help me with this scenario? Preferably something easy to use with a UI. Update: To clarify my question, changes may happen on both the local hard drive or the USB drive, so the sync process must be on both directions.

    Read the article

  • Any reason NOT to slap the 'synchronized' keyword everywhere?

    - by unknown
    In my java project, almost every non-static method I've written is synchronized. I've decided to fix up some code today, by removing most of the synchronized keywords. Right there I created several threading issues that took quite a while to fix, with no increase in performance. In the end I reverted everything. I don't see anyone else writing code with "synchronized" everywhere. So is there any reason I shouldn't have "synchronized" everywhere? What if I don't care too much about performance (ie. the method isn't called more than once every few seconds)?

    Read the article

  • What is a simple way to get ACID transactions with persistence on the local file system (in Java)?

    - by T.R.
    I'm working on a small (java) project where a website needs to maintain a (preferably comma-separated) list of registered e-mail addresses, nothing else, and be able to check if an address is in the list. I have no control over the hosting or the server's lack of database support. Prevayler seemed a good solution, but the website is a ghost town, with example code missing from just about everywhere it's supposed to be, so I'm a little wary. What other options are recommended for such a task?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >