Search Results

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

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

  • Is there any way to sync the scrollbars in a JavaFX 1.2 ListView?

    - by Xystus7777
    I have multiple listviews sidebyside. I have a way to make sure the "selectedIndex" is the same on all of them, but is there a way to make it so the scrollbar's are ALWAYS synchronized? It seems that the scrollbars WILL be synced as long as the user uses the ARROW KEYS when navigating down the listview, however, if the user HOLDS DOWN the key, OR USES THE MOUSE WHEEL, they will not be synchronized at all. Thanks in advance! Andrew Davis NASA - Kennedy Space Center

    Read the article

  • J2ME/Java: Referencing StringBuffer through Threads

    - by Jemuel Dalino
    This question might be long, but I want to provide much information. Overview: I'm creating a Stock Quotes Ticker app for Blackberry. But I'm having problems with my StringBuffer that contains an individual Stock information. Process: My app connects to our server via SocketConnection. The server sends out a formatted set of strings that contains the latest Stock trade. So whenever a new trade happens, the server will send out an individual Stock Quote of that trade. Through an InputStream I am able to read that information and place each character in a StringBuffer that is referenced by Threads. By parsing based on char3 I am able to determine a set of stock quote/information. char1 - to separate data char3 - means end of a stock quote/information sample stock quote format sent out by our server: stock_quote_name(char 1)some_data(char1)some_data(char1)(char3) My app then parses that stock quote to compare certain data and formats it how it will look like when displayed in the screen. When trades happen gradually(slow) the app works perfectly. However.. Problem: When trades happen too quickly and almost at the same time, My app is not able to handle the information sent efficiently. The StringBuffer has its contents combined with the next trade. Meaning Two stock information in one StringBuffer. field should be: Stock_quote_name some_data some_data sample of what's happening: Stock_quote_name some_data some_dataStock_quote_name some_data some_data here's my code for this part: while (-1 != (data = is.read())) { sb.append((char)data); while(3 != (data = is.read())) { sb.append((char)data); } UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { try { synchronized(UiApplication.getEventLock()) { SetStringBuffer(sb); DisplayStringBuffer(); RefreshStringBuffer(); } } catch (Exception e) { System.out.println("Error in setting stringbuffer: " + e.toString()); } } }); } public synchronized void DisplayStringBuffer() { try { //parse sb - string buffer ...... } catch(Exception ex) { System.out.println("error in DisplayStringBuffer(): " + ex.toString()); } } public synchronized void SetStringBuffer(StringBuffer dataBuffer) { this.sb =dataBuffer; System.out.println(sb); } public synchronized void RefreshStringBuffer() { this.sb.delete(0, this.sb.length()); } From what I can see, when trades happen very fast, The StringBuffer is not refreshed immediately and still has the contents of the previous trade, when i try to put new data. My Question is: Do you guys have any suggestion on how i can put data into the StringBuffer, without the next information being appended to the first content

    Read the article

  • Data not synchornizing java sockets

    - by Droid_Interceptor
    I am writing a auction server and client and using a class called BidHandler to deal with the bids another class AuctionItem to deal with the items for auction. The main problem I am having is little synchroization problem. Screen output of client server as can see from the image at 1st it takes the new bid and changes the value of the time to it, but when one the user enters 1.0 the item seems to be changed to that. But later on when the bid changes again to 15.0 it seems to stay at that price. Is there any reason for that. I have included my code below. Sorry if didnt explain this well. This is the auction client import java.io.*; import java.net.*; public class AuctionClient { private AuctionGui gui; private Socket socket; private DataInputStream dataIn; private DataOutputStream dataOut; //Auction Client constructor String name used as identifier for each client to allow server to pick the winning bidder public AuctionClient(String name,String server, int port) { gui = new AuctionGui("Bidomatic 5000"); gui.input.addKeyListener (new EnterListener(this,gui)); gui.addWindowListener(new ExitListener(this)); try { socket = new Socket(server, port); dataIn = new DataInputStream(socket.getInputStream()); dataOut = new DataOutputStream(socket.getOutputStream()); dataOut.writeUTF(name); while (true) { gui.output.append("\n"+dataIn.readUTF()); } } catch (Exception e) { e.printStackTrace(); } } public void sentBid(String bid) { try { dataOut.writeUTF(bid); } catch(IOException e) { e.printStackTrace(); } } public void disconnect() { try { socket.close(); } catch(IOException e) { e.printStackTrace(); } } public static void main (String args[]) throws IOException { if(args.length!=3) { throw new RuntimeException ("Syntax: java AuctionClient <name> <serverhost> <port>"); } int port = Integer.parseInt(args[2]); AuctionClient a = new AuctionClient(args[0],args[1],port); } } The Auction Server import java.io.*; import java.net.*; import java.util.*; public class AuctionServer { public AuctionServer(int port) throws IOException { ServerSocket server = new ServerSocket(port); while(true) { Socket client = server.accept(); DataInputStream in = new DataInputStream(client.getInputStream()); String name = in.readUTF(); System.out.println("New client "+name+" from " +client.getInetAddress()); BidHandler b = new BidHandler (name, client); b.start(); } } public static void main(String args[]) throws IOException { if(args.length != 1) throw new RuntimeException("Syntax: java AuctionServer <port>"); new AuctionServer(Integer.parseInt(args[0])); } } The BidHandler import java.net.*; import java.io.*; import java.util.*; import java.lang.Float; public class BidHandler extends Thread { Socket socket; DataInputStream in; DataOutputStream out; String name; float currentBid = 0.0f; AuctionItem paper = new AuctionItem(" News Paper ", " Free newspaper from 1990 ", 1.0f, false); protected static Vector handlers = new Vector(); public BidHandler(String name, Socket socket) throws IOException { this.name = name; this.socket = socket; in = new DataInputStream (new BufferedInputStream (socket.getInputStream())); out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); } public synchronized void run() { try { broadcast("New bidder has entered the room"); handlers.addElement(this); while(true) { broadcast(paper.getName() + paper.getDescription()+" for sale at: " +paper.getPrice()); while(paper.getStatus() == false) { String message = in.readUTF(); currentBid = Float.parseFloat(message); broadcast("Bidder entered " +currentBid); if(currentBid > paper.getPrice()) { paper.setPrice(currentBid); broadcast("New Higgest Bid is "+paper.getPrice()); } else if(currentBid < paper.getPrice()) { broadcast("Higgest Bid is "+paper.getPrice()); } else if(currentBid == paper.getPrice()) { broadcast("Higgest Bid is "+paper.getPrice()); } } } } catch(IOException ex) { System.out.println("-- Connection to user lost."); } finally { handlers.removeElement(this); broadcast(name+" left"); try { socket.close(); } catch(IOException ex) { System.out.println("-- Socket to user already closed ?"); } } } protected static void broadcast (String message) { synchronized(handlers) { Enumeration e = handlers.elements(); while(e.hasMoreElements()) { BidHandler handler = (BidHandler) e.nextElement(); try { handler.out.writeUTF(message); handler.out.flush(); } catch(IOException ex) { handler = null; } } } } } The AuctionItem Class class AuctionItem { String itemName; String itemDescription; float itemPrice; boolean itemStatus; //Create a new auction item with name, description, price and status public AuctionItem(String name, String description, float price, boolean status) { itemName = name; itemDescription = description; itemPrice = price; itemStatus = status; } //return the price of the item. public synchronized float getPrice() { return itemPrice; } //Set the price of the item. public synchronized void setPrice(float newPrice) { itemPrice = newPrice; } //Get the status of the item public synchronized boolean getStatus() { return itemStatus; } //Set the status of the item public synchronized void setStatus(boolean newStatus) { itemStatus = newStatus; } //Get the name of the item public String getName() { return itemName; } //Get the description of the item public String getDescription() { return itemDescription; } } There is also simple GUI to go with this that seems to be working fine. If anyone wants it will include the GUI code.

    Read the article

  • Issue accessing class variable from thread.

    - by James
    Hello, The code below is meant to take an arraylist of product objects as an input, spun thread for each product(and add the product to the arraylist 'products'), check product image(product.imageURL) availability, remove the products without images(remove the product from the arraylist 'products'), and return an arraylist of products with image available. package com.catgen.thread; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.catgen.Product; import com.catgen.Utils; public class ProductFilterThread extends Thread{ private Product product; private List<Product> products = new ArrayList<Product>(); public ProductFilterThread(){ } public ProductFilterThread(Product product){ this.product = product; } public synchronized void addProduct(Product product){ System.out.println("Before add: "+getProducts().size()); getProducts().add(product); System.out.println("After add: "+getProducts().size()); } public synchronized void removeProduct(Product product){ System.out.println("Before rem: "+getProducts().size()); getProducts().remove(product); System.out.println("After rem: "+getProducts().size()); } public synchronized List<Product> getProducts(){ return this.products; } public synchronized void setProducts(List<Product> products){ this.products = products; } public void run(){ boolean imageExists = Utils.fileExists(this.product.ImageURL); if(!imageExists){ System.out.println(this.product.ImageURL); removeProduct(this.product); } } public List<Product> getProductsWithImageOnly(List<Product> products){ ProductFilterThread pft = null; try{ List<ProductFilterThread> threads = new ArrayList<ProductFilterThread>(); for(Product product: products){ pft = new ProductFilterThread(product); addProduct(product); pft.start(); threads.add(pft); } Iterator<ProductFilterThread> threadsIter = threads.iterator(); while(threadsIter.hasNext()){ ProductFilterThread thread = threadsIter.next(); thread.join(); } }catch(Exception e){ e.printStackTrace(); } System.out.println("Total returned products = "+getProducts().size()); return getProducts(); } } Calling statement: displayProducts = new ProductFilterThread().getProductsWithImageOnly(displayProducts); Here, when addProduct(product) is called from within getProductsWithImageOnly(), getProducts() returns the list of products, but that's not the case(no products are returned) when the method removeProduct() is called by a thread, because of which the products without images are never removed. As a result, all the products are returned by the module whether or not the contained products have images. What can be the problem here? Thanks in advance. James.

    Read the article

  • Java java.util.ConcurrentModificationException error

    - by vijay
    Hi all, please can anybody help me solve this problem last so many days I could not able to solve this error. I tried using synchronized method and other ways but did not work so please help me Error java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(Unknown Source) at java.util.AbstractList$Itr.remove(Unknown Source) at JCA.startAnalysis(JCA.java:103) at PrgMain2.doPost(PrgMain2.java:235) Code public synchronized void startAnalysis() { //set Starting centroid positions - Start of Step 1 setInitialCentroids(); Iterator<DataPoint> n = mDataPoints.iterator(); //assign DataPoint to clusters loop1: while (true) { for (Cluster c : clusters) { c.addDataPoint(n.next()); if (!n.hasNext()) break loop1; } } //calculate E for all the clusters calcSWCSS(); //recalculate Cluster centroids - Start of Step 2 for (Cluster c : clusters) { c.getCentroid().calcCentroid(); } //recalculate E for all the clusters calcSWCSS(); // List copy = new ArrayList(originalList); //synchronized (c) { for (int i = 0; i < miter; i++) { //enter the loop for cluster 1 for (Cluster c : clusters) { for (Iterator<DataPoint> k = c.getDataPoints().iterator(); k.hasNext(); ) { // synchronized (k) { DataPoint dp = k.next(); System.out.println("Value of DP" +dp); //pick the first element of the first cluster //get the current Euclidean distance double tempEuDt = dp.getCurrentEuDt(); Cluster tempCluster = null; boolean matchFoundFlag = false; //call testEuclidean distance for all clusters for (Cluster d : clusters) { //if testEuclidean < currentEuclidean then if (tempEuDt > dp.testEuclideanDistance(d.getCentroid())) { tempEuDt = dp.testEuclideanDistance(d.getCentroid()); tempCluster = d; matchFoundFlag = true; } //if statement - Check whether the Last EuDt is > Present EuDt } //for variable 'd' - Looping between different Clusters for matching a Data Point. //add DataPoint to the cluster and calcSWCSS if (matchFoundFlag) { tempCluster.addDataPoint(dp); //k.notify(); // if(k.hasNext()) k.remove(); for (Cluster d : clusters) { d.getCentroid().calcCentroid(); } //for variable 'd' - Recalculating centroids for all Clusters calcSWCSS(); } //if statement - A Data Point is eligible for transfer between Clusters. // }// syn } //for variable 'k' - Looping through all Data Points of the current Cluster. }//for variable 'c' - Looping through all the Clusters. }//for variable 'i' - Number of iterations. // syn }

    Read the article

  • Java consistent synchronization

    - by ring0
    We are facing the following problem in a Spring service, in a multi-threaded environment: three lists are freely and independently accessed for Read once in a while (every 5 minutes), they are all updated to new values. There are some dependencies between the lists, making that, for instance, the third one should not be read while the second one is being updated and the first one already has new values ; that would break the three lists consistency. My initial idea is to make a container object having the three lists as properties. Then the synchronization would be first on that object, then one by one on each of the three lists. Some code is worth a thousands words... so here is a draft private class Sync { final List<Something> a = Collections.synchronizedList(new ArrayList<Something>()); final List<Something> b = Collections.synchronizedList(new ArrayList<Something>()); final List<Something> c = Collections.synchronizedList(new ArrayList<Something>()); } private Sync _sync = new Sync(); ... void updateRunOnceEveryFiveMinutes() { final List<Something> newa = new ArrayList<Something>(); final List<Something> newb = new ArrayList<Something>(); final List<Something> newc = new ArrayList<Something>(); ...building newa, newb and newc... synchronized(_sync) { synchronized(_sync.a) { _synch.a.clear(); _synch.a.addAll(newa); } synchronized(_sync.b) { ...same with newb... } synchronized(_sync.c) { ...same with newc... } } // Next is accessed by clients public List<Something> getListA() { return _sync.a; } public List<Something> getListB() { ...same with b... } public List<Something> getListC() { ...same with c... } The question would be, is this draft safe (no deadlock, data consistency)? would you have a better implementation suggestion for that specific problem? update Changed the order of _sync synchronization and newa... building. Thanks

    Read the article

  • what does synchronization mean in hibernate..

    - by abc
    i read that upon session.flush() The data will be synchronized (but not committed) when session.flush() is called what is synchronized with what.. whether it is DB state that will come to memory by querying or memory state will be copied to Db ? clarify this plz..

    Read the article

  • Singleton & Multithreading in Java

    - by vivek jagtap
    What is the preferred way to work with Singleton class in multithreaded environment? Suppose if I have 3 thread, and all they try to access getInstance() method of singleton class at the same time - What would happen if no synchronization is maintained? Is it good practice to use synchronized getInstance() method or use synchronized block inside getInstance(). Please advise if there is any other way out.

    Read the article

  • How solve consumer/producer task using semaphores

    - by user1074896
    I have SimpleProducerConsumer class that illustrate consumer/producer problem (I am not sure that it's correct). public class SimpleProducerConsumer { private Stack<Object> stack = new Stack<Object>(); private static final int STACK_MAX_SIZE = 10; public static void main(String[] args) { SimpleProducerConsumer pc = new SimpleProducerConsumer(); new Thread(pc.new Producer(), "p1").start(); new Thread(pc.new Producer(), "p2").start(); new Thread(pc.new Consumer(), "c1").start(); new Thread(pc.new Consumer(), "c2").start(); new Thread(pc.new Consumer(), "c3").start(); } public synchronized void push(Object d) { while (stack.size() >= STACK_MAX_SIZE) try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } stack.push(new Object()); System.out.println("push " + Thread.currentThread().getName() + " " + stack.size()); notify(); } public synchronized Object pop() { while (stack.size() == 0) try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } stack.pop(); System.out.println("pop " + Thread.currentThread().getName() + " " + stack.size()); notify(); return null; } class Consumer implements Runnable { @Override public void run() { while (true) { pop(); } } } class Producer implements Runnable { @Override public void run() { while (true) { push(new Object()); } } } } I found simple realization of semaphore(here:http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html I know that there is concurrency package) How I need to change code to exchange java objects monitors to my custom semaphore. (To illustrate C/P problem using semaphores) Semaphore: class Semaphore { private int counter; public Semaphore() { this(0); } public Semaphore(int i) { if (i < 0) throw new IllegalArgumentException(i + " < 0"); counter = i; } public synchronized void release() { if (counter == 0) { notify(); } counter++; } public synchronized void acquire() throws InterruptedException { while (counter == 0) { wait(); } counter--; } }

    Read the article

  • What is the correct way to synchronize a shared, static object in Java?

    - by johnrock
    This is a question concerning what is the proper way to synchronize a shared object in java. One caveat is that the object that I want to share must be accessed from static methods. My question is, If I synchronize on a static field, does that lock the class the field belongs to similar to the way a synchronized static method would? Or, will this only lock the field itself? In my specific example I am asking: Will calling PayloadService.getPayload() or PayloadService.setPayload() lock PayloadService.payload? Or will it lock the entire PayloadService class? public class PayloadService extends Service { private static PayloadDTO payload = new PayloadDTO(); public static void setPayload(PayloadDTO payload){ synchronized(PayloadService.payload){ PayloadService.payload = payload; } } public static PayloadDTO getPayload() { synchronized(PayloadService.payload){ return PayloadService.payload ; } } ... Is this a correct/acceptable approach ? In my example the PayloadService is a separate thread, updating the payload object at regular intervals - other threads need to call PayloadService.getPayload() at random intervals to get the latest data and I need to make sure that they don't lock the PayloadService from carrying out its timer task

    Read the article

  • Java 1.4 singleton containing a mutable field

    - by Philippe
    Hi, I'm working on a legacy Java 1.4 project, and I have a factory that instantiates a csv file parser as a singleton. In my csv file parser, however, I have a HashSet that will store objects created from each line of my CSV file. All that will be used by a web application, and users will be uploading CSV files, possibly concurrently. Now my question is : what is the best way to prevent my list of objects to be modified by 2 users ? So far, I'm doing the following : final class MyParser { private File csvFile = null; private static Set myObjects = Collections.synchronizedSet(new HashSet); public synchronized void setFile(File file) { this.csvFile = file; } public void parse() FileReader fr = null; try { fr = new FileReader(csvFile); synchronized(myObjects) { myObjects.clear(); while(...) { // foreach line of my CSV, create a "MyObject" myObjects.add(new MyObject(...)); } } } catch (Exception e) { //... } } } Should I leave the lock only on the myObjects Set, or should I declare the whole parse() method as synchronized ? Also, how should I synchronize - both - the setting of the csvFile and the parsing ? I feel like my actual design is broken because threads could modify the csv file several times while a possibly long parse process is running. I hope I'm being clear enough, because myself am a bit confused on those multi-synchronization issues. Thanks ;-)

    Read the article

  • Java Performance measurement

    - by portoalet
    Hi, I am doing some Java performance comparison between my classes, and wondering if there is some sort of Java Performance Framework to make writing performance measurement code easier? I.e, what I am doing now is trying to measure what effect does it have having a method as "synchronized" as in PseudoRandomUsingSynch.nextInt() compared to using an AtomicInteger as my "synchronizer". So I am trying to measure how long it takes to generate random integers using 3 threads accessing a synchronized method looping for say 10000 times. I am sure there is a much better way doing this. Can you please enlighten me? :) public static void main( String [] args ) throws InterruptedException, ExecutionException { PseudoRandomUsingSynch rand1 = new PseudoRandomUsingSynch((int)System.currentTimeMillis()); int n = 3; ExecutorService execService = Executors.newFixedThreadPool(n); long timeBefore = System.currentTimeMillis(); for(int idx=0; idx<100000; ++idx) { Future<Integer> future = execService.submit(rand1); Future<Integer> future1 = execService.submit(rand1); Future<Integer> future2 = execService.submit(rand1); int random1 = future.get(); int random2 = future1.get(); int random3 = future2.get(); } long timeAfter = System.currentTimeMillis(); long elapsed = timeAfter - timeBefore; out.println("elapsed:" + elapsed); } the class public class PseudoRandomUsingSynch implements Callable<Integer> { private int seed; public PseudoRandomUsingSynch(int s) { seed = s; } public synchronized int nextInt(int n) { byte [] s = DonsUtil.intToByteArray(seed); SecureRandom secureRandom = new SecureRandom(s); return ( secureRandom.nextInt() % n ); } @Override public Integer call() throws Exception { return nextInt((int)System.currentTimeMillis()); } } Regards

    Read the article

  • how to pause and stop a changing ImageView

    - by user270811
    hi, i have an ImageView in which the picture switches every 5s, i am trying to add a pause and resume button that can stop and restart the action. i am using a Handler, Runnable, and postDelay() for image switch, and i put the code on onResume. i am thinking about using wait and notify for the pause and resume, but that would mean creating an extra thread. so far for the thread, i have this: class RecipeDisplayThread extends Thread { boolean pleaseWait = false; // This method is called when the thread runs public void run() { while (true) { // Do work // Check if should wait synchronized (this) { while (pleaseWait) { try { wait(); } catch (Exception e) { } } } // Do work } } } and in the main activity's onCreate(): Button pauseButton = (Button) findViewById(R.id.pause); pauseButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { while (true) { synchronized (thread) { thread.pleaseWait = true; } } } }); Button resumeButton = (Button) findViewById(R.id.resume); resumeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { while (true) { // Resume the thread synchronized (thread) { thread.pleaseWait = false; thread.notify(); } } } }); the pause button seems to work, but then after that i can't press any other button, such as the resume button. thanks.

    Read the article

  • SQL Server Database In Single User Mode after Failover

    - by jlichauc
    Here is a weird situation we experienced with a SQL Server 2008 Database Mirroring Failover. We have a pair of mirrored databases running in high-availability mode and both the principal and mirror showed as synchronized. As part of some maintenance I triggered a manual failover of the principal to the mirror. However after the failover the principal was now in single-user mode instead of the expected "Principal/Synchronized" state we usually get. The database had been in multi-user mode on the previous principal before this had happened. We ended up stopping all applications, restarting the SQL Server instances, and executing "ALTER DATABASE ... SET MULTI_USER" to bring the database back to the expected "Principal/Synchronized" state in a multi-user mode. Question. Does anyone know where SQL Server stores information about whether a database should be in single-user mode or not? I'm wondering if there is some system database or table that has this setting recorded somewhere. In particular we had an incident once with the database on the original principal (the one I was failing over to) where when trying to detach the database it was put into single-user mode. I'm wondering if that setting is cached somewhere and is the reason that SQL Server put it back into single-user mode after a failover.

    Read the article

  • How to fix IllegalStateException error when trying to update a listview?

    - by Michael Vetrano
    Hi guys, I am trying to get this code to run, but I get an IllegalStateException when I run this code saying that the content of the listview wasn't notified, yet I have a notification upon updating the data. This is a custom listview adapter. Here is the relevant part of my code: class LoadingThread extends Thread { public void run() { int itemsOriginallyLoaded = 0; synchronized( items ) { itemsOriginallyLoaded = items.size(); } for( int i = itemsOriginallyLoaded ; i < itemsToLoad ; ++i ) { Log.d( LOG_TAG, "Loading item #"+i ); //String item = "FAIL"; //try { String item = "FAIL"; try { item = stockGrabber.getStockString(dataSource.get(i)); } catch (ApiException e) { Log.e(LOG_TAG, "Problem making API request", e); } catch (ParseException e) { Log.e(LOG_TAG, "Problem parsing API request", e); } //} catch (ApiException e) { // Log.e(TAG, "Problem making API request", e); //} catch (ParseException e) { // Log.e(TAG, "Problem parsing API request", e); //} synchronized( items ) { items.add( item ); } itemsLoaded = i+1; uiHandler.post( updateTask ); Log.d( LOG_TAG, "Published item #"+i ); } if( itemsLoaded >= ( dataSource.size() - 1 ) ) allItemsLoaded = true; synchronized( loading ) { loading = Boolean.FALSE; } } } class UIUpdateTask implements Runnable { public void run() { Log.d( LOG_TAG, "Publishing progress" ); notifyDataSetChanged(); } }

    Read the article

  • Message sent to deallocated instance which has never been released

    - by Jakub
    Hello, I started dealing with NSOperations and (as usual with concurrency) I'm observing strange behaviour. In my class I've got an instance variable: NSMutableArray *postResultsArray; when one button in the UI is pressed I initialize the array: postResultsArray = [NSMutableArray array]; and setup the operations (together with dependencies). In the operations I create a custom object and try to add to the array: PostResult *result = [[PostResult alloc] initWithServiceName:@"Sth" andResult:someResult]; [self.postResultsArray addObject:result]; and while adding I get: -[CFArray retain]: message sent to deallocated instance 0x3b40c30 which is strange as I don't release the array anywhere in my code (I did, but when the problem started to appear I commented all the release operations to be sure that they are not the case). I also used to have @synchronized section like below: PostResult *result = [[PostResult alloc] initWithServiceName:@"Sth" andResult:someResult]; @synchronized (self.postResultsArray) { [self.postResultsArray addObject:result]; } but the problem was the same (however, the error was for the synchronized operation). Any ideas what I may be doing wrong?

    Read the article

  • Getting problem in threading in JAVA

    - by chetans
    In this program i want to stop GenerateImage & MovingImage Thread both... And i want to start those threads from begining. Can u send me the solution? Here is the code........ package Game; import java.applet.Applet; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.net.MalformedURLException; import java.net.URL; public class ThreadInApplet extends Applet implements KeyListener { private static final long serialVersionUID = 1L; Image[] asteroidImage; Image spaceshipImage; String levelstr="Easy Level"; int[] XPos,YPos; int number=0,XPosOfSpaceship,YPosOfSpaceship,NoOfObstacles=5,speed=1,level=1,spaceBtnPressdCntr=0; boolean gameStart=false,pauseGame=false,collideUp=false,collideDown=false,collideLeft=false,collideRight=false; private Image offScreenImage; private Dimension offScreenSize; private Graphics offScreenGraphics; Thread GenerateImages,MoveImages; public void init() { try { GenerateImages=new Thread () //thread to create obstacles { synchronized public void run () { for(int g=0;g<NoOfObstacles;g++) { try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } number++; // Temporary counter to count the no of obstacles created } } } ; MoveImages=new Thread () //thread to move obstacles { @SuppressWarnings("deprecation") synchronized public void run () { while(YPos[NoOfObstacles-1]!=600) { pauseGame=false; if(collide()==true) { GenerateImages.suspend(); repaint(); } else GenerateImages.resume(); for(int l=0;l<number;l++) { if(collide()==false) YPos[l]++; else GenerateImages.suspend(); } repaint(); try { sleep(speed); } catch (InterruptedException e) { e.printStackTrace(); } } if(YPos[NoOfObstacles-1]>=600) //level complete state { level++; try { levelUpdation(level); System.out.println("aahe"); } catch (MalformedURLException e) { e.printStackTrace(); } repaint(); } } }; initialPos(); spaceshipImage=getImage(new URL(getCodeBase(),"images/space.png")); for(int i=0;i<NoOfObstacles;i++) { asteroidImage[i]=getImage(new URL(getCodeBase(),"images/asteroid.png")); XPos[i]=(int) (Math.random()*700); YPos[i]=0; } MediaTracker tracker = new MediaTracker (this); for(int i=0;i<NoOfObstacles;i++) { tracker.addImage (asteroidImage[i], 0); } } catch (MalformedURLException e) { e.printStackTrace(); } setBackground(Color.black); addKeyListener(this); } //Sets initial positions of spaceship & obstacle images------------------------------------------------------ public void initialPos() throws MalformedURLException { asteroidImage=new Image[NoOfObstacles]; XPos=new int[NoOfObstacles]; YPos=new int[NoOfObstacles]; XPosOfSpaceship=getWidth()/2-35; YPosOfSpaceship=getHeight()-100; collideUp = false; collideDown=false; collideLeft=false; collideRight=false; } //level finished updations------------------------------------------------------------------------------ @SuppressWarnings("deprecation") public void levelUpdation(int level) throws MalformedURLException { NoOfObstacles=NoOfObstacles+20; speed=speed-3; System.out.println(NoOfObstacles+" "+speed); pauseGame=true; initialPos(); repaint(); } //paint method of graphics to print the messages--------------------------------------------------------- public void paint(Graphics g) { g.setColor(Color.white); if(gameStart==false) { g.drawString("SPACE to start", (getWidth()/2)-15, getHeight()/2); g.drawString(levelstr, (getWidth()/2), getHeight()/2+20); } if(level>1) { if(level==2) levelstr="Medium Level"; else levelstr="High Level"; g.drawString("Level Complete ", (getWidth()/2)-15, getHeight()/2); g.drawString(levelstr, (getWidth()/2), getHeight()/2+20); //g.drawString("SPACE to start", (getWidth()/2)-15, getHeight()/2+40); } for(int n=0;n<number;n++) { if(n>0) g.drawImage(asteroidImage[n],XPos[n],YPos[n],this); } g.drawImage(spaceshipImage,XPosOfSpaceship,YPosOfSpaceship,this); } //update method of graphics to print the messages--------------------------------------------------------- @SuppressWarnings("deprecation") public void update(Graphics g) { Dimension d = size(); if((offScreenImage == null) || (d.width != offScreenSize.width) || (d.height != offScreenSize.height)) { offScreenImage = createImage(d.width, d.height); offScreenSize = d; offScreenGraphics = offScreenImage.getGraphics(); } offScreenGraphics.clearRect(0, 0, d.width, d.height); paint(offScreenGraphics); g.drawImage(offScreenImage, 0, 0, null); } public void keyReleased(KeyEvent arg0){} public void keyTyped(KeyEvent arg0) {} //---------------------Key pressed event to start game & to move the spaceship-------------------------------------- public void keyPressed(KeyEvent e) { if(e.getKeyCode()==32) { spaceBtnPressdCntr++; if(spaceBtnPressdCntr==1) { gameStart=true; GenerateImages.start(); MoveImages.start(); } } if(gameStart==true) { if(e.getKeyCode()==37) { new Thread () { @SuppressWarnings("deprecation") synchronized public void run () { for(int cnt1=1;cnt1<=10;cnt1++) { if(collide()==true && collideLeft == true) { GenerateImages.suspend(); } else { if(XPosOfSpaceship>0) XPosOfSpaceship--; } } repaint(); } }.start(); } if(e.getKeyCode()==38) { new Thread () { @SuppressWarnings("deprecation") synchronized public void run () { for(int cnt1=1;cnt1<=10;cnt1++) { if(collide()==true && collideUp == true) { GenerateImages.suspend(); } else { if(YPosOfSpaceship>10) YPosOfSpaceship--; } } repaint(); } }.start(); } if(e.getKeyCode()==39) { new Thread () { @SuppressWarnings("deprecation") synchronized public void run () { for(int cnt1=1;cnt1<=10;cnt1++) { if(collide()==true && collideRight == true) { GenerateImages.suspend(); } else { if(XPosOfSpaceship<750) XPosOfSpaceship++; } } repaint(); } }.start(); } if(e.getKeyCode()==40) { new Thread () { @SuppressWarnings("deprecation") synchronized public void run () { for(int cnt1=1;cnt1<=10;cnt1++) { if(collide()==true && collideDown == true) { GenerateImages.suspend(); } else { if(YPosOfSpaceship<550) YPosOfSpaceship++; } } repaint(); } }.start(); } } } //------------------------------Collision checking between Spaceship & obstacles------------------------------ public boolean collide() { int x1,y1,x2,y2,x3,y3,x4,y4; //coordinates of obstacles int a1,b1,a2,b2,a3,b3,a4,b4; //coordinates of spaceship a1 =XPosOfSpaceship; b1=YPosOfSpaceship; a2=a1+spaceshipImage.getWidth(this); b2=b1; a3=a1; b3=b1+spaceshipImage.getHeight(this); a4=a2; b4=b3; for(int a=0;a<number;a++) { x1 =XPos[a]; y1=YPos[a]; x2=x1+asteroidImage[a].getWidth(this); y2=y1; x3=x1; y3=y1+asteroidImage[a].getHeight(this); x4=x2; y4=y3; /********checking asteroid touch spaceship from up direction********/ if(y3==b1 && x4>=a1 && x4<=a2) { collideUp = true; collideDown=false; collideLeft=false; collideRight=false; return(true); } if(y3==b1 && x3>=a1 && x3<=a2) { collideUp = true; collideDown=false; collideLeft=false; collideRight=false; return(true); } /********checking asteroid touch spaceship from left direction******/ if(x2==a1 && y4>=b1 && y4<=b3) { collideLeft=true; collideUp = false; collideDown=false; collideRight=false; return(true); } if(x2==a1 && y2>=b1 && y2<=b3) { collideLeft=true; collideUp = false; collideDown=false; collideRight=false; return(true); } /********checking asteroid touch spaceship from right direction*****/ if(x1==a2 && y3>=b2 && y3<=b4) { collideRight=true; collideLeft=false; collideUp = false; collideDown=false; return(true); } if(x1==a2 && y1>=b2 && y1<=b4) { collideRight=true; collideLeft=false; collideUp = false; collideDown=false; return(true); } /********checking asteroid touch spaceship from down direction*****/ if(y1==b3 && x2>=a3 && x2<=a4) { collideDown=true; collideRight=false; collideLeft=false; collideUp = false; return(true); } if(y1==b3 && x1>=a3 && x1<=a4) { collideDown=true; collideRight=false; collideLeft=false; collideUp = false; return(true); } } return(false); } }

    Read the article

  • java - question about thread abortion and deadlock - volatile keyword

    - by Tiyoal
    Hello all, I am having some troubles to understand how I have to stop a running thread. I'll try to explain it by example. Assume the following class: public class MyThread extends Thread { protected volatile boolean running = true; public void run() { while (running) { synchronized (someObject) { while (someObject.someCondition() == false && running) { try { someObject.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // do something useful with someObject } } } public void halt() { running = false; interrupt(); } } Assume the thread is running and the following statement is evaluated to true: while (someObject.someCondition() == false && running) Then, another thread calls MyThread.halt(). Eventhough this function sets 'running' to false (which is a volatile boolean) and interrupts the thread, the following statement is still executed: someObject.wait(); We have a deadlock. The thread will never be halted. Then I came up with this, but I am not sure if it is correct: public class MyThread extends Thread { protected volatile boolean running = true; public void run() { while (running) { synchronized (someObject) { while (someObject.someCondition() == false && running) { try { someObject.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // do something useful with someObject } } } public void halt() { running = false; synchronized(someObject) { interrupt(); } } } Is this correct? Is this the most common way to do this? This seems like an obvious question, but I fail to come up with a solution. Thanks a lot for your help.

    Read the article

  • A member variable's hashCode() value is different

    - by Jacques René Mesrine
    There's a piece of code that looks like this. The problem is that during bootup, 2 initialization takes place. (1) Some method does a reflection on ForumRepository & performs a newInstance() purely to invoke #setCacheEngine. (2) Another method following that invokes #start(). I am noticing that the hashCode of the #cache member variable is different sometimes in some weird scenarios. Since only 1 piece of code invokes #setCacheEngine, how can the hashCode change during runtime (I am assuming that a different instance will have a different hashCode). Is there a bug here somewhere ? public class ForumRepository implements Cacheable { private static CacheEngine cache; private static ForumRepository instance; public void setCacheEngine(CacheEngine engine) { cache = engine; } public synchronized static void start() { instance = new ForumRepository(); } public synchronized static void addForum( ... ) { cache.add( .. ); System.out.println( cache.hashCode() ); // snipped } public synchronized static void getForum( ... ) { ... cache.get( .. ); System.out.println( cache.hashCode() ); // snipped } }

    Read the article

  • synchronizing reads to a java collection

    - by jeff
    so i want to have an arraylist that stores a series of stock quotes. but i keep track of bid price, ask price and last price for each. of course at any time, the bid ask or last of a given stock can change. i have one thread that updates the prices and one that reads them. i want to make sure that when reading no other thread is updating a price. so i looked at synchronized collection. but that seems to only prevent reading while another thread is adding or deleting an entry to the arraylist. so now i'm onto the wrapper approach: public class Qte_List { private final ArrayList<Qte> the_list; public void UpdateBid(String p_sym, double p_bid){ synchronized (the_list){ Qte q = Qte.FindBySym(the_list, p_sym); q.bid=p_bid;} } public double ReadBid(String p_sym){ synchronized (the_list){ Qte q = Qte.FindBySym(the_list, p_sym); return q.bid;} } so what i want to accomplish with this is only one thread can be doing anything - reading or updating an the_list's contents - at one time. am i approach this right? thanks.

    Read the article

  • mvc design in a card game

    - by Hong
    I'm trying to make a card game. some classes I have are: CardModel, CardView; DeckModel, DeckView. The deck model has a list of card model, According to MVC, if I want to send a card to a deck, I can add the card model to the deck model, and the card view will be added to the deck view by a event handler. So I have a addCard(CardModel m) in the DeckModel class, but if I want to send a event to add the card view of that model to the deck view, I only know let the model has a reference to view. So the question is: If the card model and deck model have to have a reference to their view classes to do it? If not, how to do it better? Update, the code: public class DeckModel { private ArrayList<CardModel> cards; private ArrayList<EventHandler> actionEventHandlerList; public void addCard(CardModel card){ cards.add(card); //processEvent(event x); //must I pass a event that contain card view here? } CardModel getCards(int index){ return cards.get(index); } public synchronized void addEventHandler(EventHandler l){ if(actionEventHandlerList == null) actionEventHandlerList = new ArrayList<EventHandler>(); if(!actionEventHandlerList.contains(l)) actionEventHandlerList.add(l); } public synchronized void removeEventHandler(EventHandler l){ if(actionEventHandlerList!= null && actionEventHandlerList.contains(l)) actionEventHandlerList.remove(l); } private void processEvent(Event e){ ArrayList list; synchronized(this){ if(actionEventHandlerList!= null) list = (ArrayList)actionEventHandlerList.clone(); else return; } for(int i=0; i<actionEventHandlerList.size(); ++i){ actionEventHandlerList.get(i).handle(e); } } }

    Read the article

  • How do I make this Java code operate properly? [Multi-threaded, race condition]

    - by Fixee
    I got this code from a student, and it does not work properly because of a race condition involving x++ and x--. He added synchronized to the run() method trying to get rid of this bug, but obviously this only excludes threads from entering run() on the same object (which was never a problem in the first place) but doesn't prevent independent objects from updating the same static variable x at the same time. public class DataRace implements Runnable { static volatile int x; public synchronized void run() { for (int i = 0; i < 10000; i++) { x++; x--; } } public static void main(String[] args) throws Exception { Thread [] threads = new Thread[100]; for (int i = 0; i < threads.length; i++) threads[i] = new Thread(new DataRace()); for (int i = 0; i < threads.length; i++) threads[i].start(); for (int i = 0; i < threads.length; i++) threads[i].join(); System.out.println(x); // x not always 0! } } Since we cannot synchronize on x (because it is primitive), the best solution I can think of is to create a new static object like static String lock = ""; and enclose the x++ and x-- within a synchronized block, locking on lock. But this seems really awkward. Is there a better way?

    Read the article

  • java.util.ConcurrentModificationException when serializing non thread-safe maps

    - by [email protected]
    We have got some questions related to exceptions thrown during a map serialization like the following one (in this example, for a LRUMap): java.util.ConcurrentModificationExceptionat org.apache.commons.collections.SequencedHashMap$OrderedIterator.next(Unknown Source)at org.apache.commons.collections.LRUMap.writeExternal(Unknown Source)at java.io.ObjectOutputStream.writeExternalData(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java(Inlined CompiledCode))at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java(Inlined CompiledCode))at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java(Inlined CompiledCode))at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java(Compiled Code))at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java(Compiled Code))at com.tangosol.util.ExternalizableHelper.writeSerializable(ExternalizableHelper.java(InlinedCompiled Code))at com.tangosol.util.ExternalizableHelper.writeObjectInternal(ExternalizableHelper.java(Compiled Code))at com.tangosol.util.ExternalizableHelper.serializeInternal(ExternalizableHelper.java(Compiled Code))at com.tangosol.util.ExternalizableHelper.toBinary(ExternalizableHelper.java(InlinedCompiled Code))at com.tangosol.util.ExternalizableHelper.toBinary(ExternalizableHelper.java(InlinedCompiled Code))at com.tangosol.coherence.servlet.TraditionalHttpSessionModel$OptimizedHolder.serializeValue(TraditionalHttpSessionModel.java(Inlined Compiled Code))at com.tangosol.coherence.servlet.TraditionalHttpSessionModel$OptimizedHolder.getBinary(TraditionalHttpSessionModel.java(Compiled Code)) This is caused because LRUMap is not thread safe, so if another thread is modifying the content of that same map while serialization is in progress, then the ConcurrentModificationException will be thrown. Also, the map must be synchronized. Other structures like java.util.HashMap are not thread safe too. To avoid this kind of problems, it is recommended to use a thread-safe and synchronized map such as java.util.Map, java.util.Hashtable or com.tangosol.util.SafeHashMap. You may also need to use the synchronizedMap(Map) method from Class java.util.Collections.  

    Read the article

  • Execute a SSIS package in Sync or Async mode from SQL Server 2012

    - by Davide Mauri
    Today I had to schedule a package stored in the shiny new SSIS Catalog store that can be enabled with SQL Server 2012. (http://msdn.microsoft.com/en-us/library/hh479588(v=SQL.110).aspx) Once your packages are stored here, they will be executed using the new stored procedures created for this purpose. This is the script that will get executed if you try to execute your packages right from management studio or through a SQL Server Agent job, will be similar to the following: Declare @execution_id bigint EXEC [SSISDB].[catalog].[create_execution] @package_name='my_package.dtsx', @execution_id=@execution_id OUTPUT, @folder_name=N'BI', @project_name=N'DWH', @use32bitruntime=False, @reference_id=Null Select @execution_id DECLARE @var0 smallint = 1 EXEC [SSISDB].[catalog].[set_execution_parameter_value] @execution_id,  @object_type=50, @parameter_name=N'LOGGING_LEVEL', @parameter_value=@var0 DECLARE @var1 bit = 0 EXEC [SSISDB].[catalog].[set_execution_parameter_value] @execution_id,  @object_type=50, @parameter_name=N'DUMP_ON_ERROR', @parameter_value=@var1 EXEC [SSISDB].[catalog].[start_execution] @execution_id GO The problem here is that the procedure will simply start the execution of the package and will return as soon as the package as been started…thus giving you the opportunity to execute packages asynchrously from your T-SQL code. This is just *great*, but what happens if I what to execute a package and WAIT for it to finish (and thus having a synchronous execution of it)? You have to be sure that you add the “SYNCHRONIZED” parameter to the package execution. Before the start_execution procedure: exec [SSISDB].[catalog].[set_execution_parameter_value] @execution_id,  @object_type=50, @parameter_name=N'SYNCHRONIZED', @parameter_value=1 And that’s it . PS From the RC0, the SYNCHRONIZED parameter is automatically added each time you schedule a package execution through the SQL Server Agent. If you’re using an external scheduler, just keep this post in mind .

    Read the article

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