Search Results

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

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

  • Am I correct in my assumption about synchronized block?

    - by kunjaan
    I have a method shout() with a synchronized block. private void shout(){ System.out.println("SHOUT " + Thread.currentThread().getName()); synchronized(this){ System.out.println("Synchronized Shout" + Thread.currentThread().getName()); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Synchronized Shout" + Thread.currentThread().getName()); } } If I have two Threads that run this method, am I correct in assuming that the two "Synchronized Shout" will always appear one after the other? There can be no other statements in between the "Synchronized Shout"?

    Read the article

  • synchronized in java - Proper use

    - by ZoharYosef
    I'm building a simple program to use in multi processes (Threads). My question is more to understand - when I have to use a reserved word synchronized? Do I need to use this word in any method that affects the bone variables? I know I can put it on any method that is not static, but I want to understand more. thank you! here is the code: public class Container { // *** data members *** public static final int INIT_SIZE=10; // the first (init) size of the set. public static final int RESCALE=10; // the re-scale factor of this set. private int _sp=0; public Object[] _data; /************ Constructors ************/ public Container(){ _sp=0; _data = new Object[INIT_SIZE]; } public Container(Container other) { // copy constructor this(); for(int i=0;i<other.size();i++) this.add(other.at(i)); } /** return true is this collection is empty, else return false. */ public synchronized boolean isEmpty() {return _sp==0;} /** add an Object to this set */ public synchronized void add (Object p){ if (_sp==_data.length) rescale(RESCALE); _data[_sp] = p; // shellow copy semantic. _sp++; } /** returns the actual amount of Objects contained in this collection */ public synchronized int size() {return _sp;} /** returns true if this container contains an element which is equals to ob */ public synchronized boolean isMember(Object ob) { return get(ob)!=-1; } /** return the index of the first object which equals ob, if none returns -1 */ public synchronized int get(Object ob) { int ans=-1; for(int i=0;i<size();i=i+1) if(at(i).equals(ob)) return i; return ans; } /** returns the element located at the ind place in this container (null if out of range) */ public synchronized Object at(int p){ if (p>=0 && p<size()) return _data[p]; else return null; }

    Read the article

  • Java synchronized method lock on object, or method?

    - by wuntee
    If I have 2 synchronized methods in the same class, but each accessing different variables, can 2 threads access those 2 methods at the same time? Does the lock occur on the object, or does it get as specific as the variables inside the synchronized method? Example: class x{ private int a; private int b; public synchronized void addA(){ a++; } public synchronized void addB(){ b++; } } Can 2 threads access the same instance of class x performing x.addA() and x.addB() at the same time?

    Read the article

  • Volatile or synchronized for primitive type?

    - by DKSRathore
    In java, assignment is atomic if the size of the variable is less that or equal to 32 bits but is not if more than 32 bits. What(volatile/synchronized) would be more efficient to use in case of double or long assignment. like, volatile double x = y; synchronized is not applicable with primitive argument. How do i use synchronized in this case. Of course I don't want to lock my class. so this should not be used.

    Read the article

  • Mixing synchronized() with ReentrantLock.lock()

    - by yarvin
    In Java, do ReentrantLock.lock() and ReetrantLock.unlock() use the same locking mechanism as synchronized()? My guess is "No," but I'm hoping to be wrong. Example: Imagine that Thread 1 and Thread 2 both have access to: ReentrantLock lock = new ReentrantLock(); Thread 1 runs: synchronized (lock) { // blah } Thread 2 runs: lock.lock(); try { // blah } finally { lock.unlock(); } Assume Thread 1 reaches its part first, then Thread 2 before Thread 1 is finished: will Thread 2 wait for Thread 1 to leave the synchronized() block, or will it go ahead and run?

    Read the article

  • Difference in output from use of synchronized keyword and join()

    - by user2964080
    I have 2 classes, public class Account { private int balance = 50; public int getBalance() { return balance; } public void withdraw(int amt){ this.balance -= amt; } } and public class DangerousAccount implements Runnable{ private Account acct = new Account(); public static void main(String[] args) throws InterruptedException{ DangerousAccount target = new DangerousAccount(); Thread t1 = new Thread(target); Thread t2 = new Thread(target); t1.setName("Ravi"); t2.setName("Prakash"); t1.start(); /* #1 t1.join(); */ t2.start(); } public void run(){ for(int i=0; i<5; i++){ makeWithdrawl(10); if(acct.getBalance() < 0) System.out.println("Account Overdrawn"); } } public void makeWithdrawl(int amt){ if(acct.getBalance() >= amt){ System.out.println(Thread.currentThread().getName() + " is going to withdraw"); try{ Thread.sleep(500); }catch(InterruptedException e){ e.printStackTrace(); } acct.withdraw(amt); System.out.println(Thread.currentThread().getName() + " has finished the withdrawl"); }else{ System.out.println("Not Enough Money For " + Thread.currentThread().getName() + " to withdraw"); } } } I tried adding synchronized keyword in makeWithdrawl method public synchronized void makeWithdrawl(int amt){ and I keep getting this output as many times I try Ravi is going to withdraw Ravi has finished the withdrawl Ravi is going to withdraw Ravi has finished the withdrawl Ravi is going to withdraw Ravi has finished the withdrawl Ravi is going to withdraw Ravi has finished the withdrawl Ravi is going to withdraw Ravi has finished the withdrawl Not Enough Money For Prakash to withdraw Not Enough Money For Prakash to withdraw Not Enough Money For Prakash to withdraw Not Enough Money For Prakash to withdraw Not Enough Money For Prakash to withdraw This shows that only Thread t1 is working... If I un-comment the the line saying t1.join(); I get the same output. So how does synchronized differ from join() ? If I don't use synchronize keyword or join() I get various outputs like Ravi is going to withdraw Prakash is going to withdraw Prakash has finished the withdrawl Ravi has finished the withdrawl Prakash is going to withdraw Ravi is going to withdraw Prakash has finished the withdrawl Ravi has finished the withdrawl Prakash is going to withdraw Ravi is going to withdraw Prakash has finished the withdrawl Ravi has finished the withdrawl Account Overdrawn Account Overdrawn Not Enough Money For Ravi to withdraw Account Overdrawn Not Enough Money For Prakash to withdraw Account Overdrawn Not Enough Money For Ravi to withdraw Account Overdrawn Not Enough Money For Prakash to withdraw Account Overdrawn So how does the output from synchronized differ from join() ?

    Read the article

  • Java Synchronized Write Block

    - by ikurtz
    im new to java and i have a question regarding Synchronized. i have the following code for writing to network (simple implementation for now): public void networkSendData(byte[] data){ try { out.write(data); out.flush(); } catch (IOException e) { } } i was wondering if there is a need for block level Synchronized here as im am writing the whole data at once. or is there a chance for race condition? i ask because the data to write is coming for multiple sources. thank you.

    Read the article

  • two android threads and not synchronized data

    - by Sponge
    i have a (perhaps stupid) question: im using 2 threads, one is writing floats and one is reading this floats permanently. my question is, what could happen worse when i dont synchronize them? it would be no problem if some of the values would not be correct because they switch just a little every write operation. im running the application this way at the moment and dont have any problems so i want to know what could happen worse? a read/write conflict would cause a number like 12345 which is written to 54321 and red at the same time appear for example as 54345 ? or could happen something worse? (i dont want to use synchronization to keep the code as fast as possible)

    Read the article

  • Keeping local folders synchronized

    - by Earthling
    After repeatedly losing data on encrypted drives due to some trivial combination of software and hardware failure, I would like to know if there is a simple tool that keeps local folders synchronized. Like a local "cloud" service that runs on one computer and synchronizes any changes in one folder to the other folder as soon as both folders are available. That way I can keep a copy of the most important files on a different hard-drive.

    Read the article

  • Empty Synchronized method in game loop

    - by Shijima
    I am studying the gameloop used in Replica Island to understand a bit about Android game development. The main loop has the below logic... GameThread.java (note the variable names in sample code dont match exact source code) while (!finished) { if (objectManager != null) { renderer.waitDrawingComplete(); //Do more gameloop stuff after drawing is complete... } } I was curious to see what waitDrawingComplete actually does, but found its just an empty syncrhonized method! I guess it does nothing, am I missing something here? GameRenderer.java line 328 public synchronized void waitDrawingComplete() { } Source code can be checked out here with SVN if you feel like having a look: https://code.google.com/p/replicaisland/source/checkout

    Read the article

  • Synchronized Property Changes (Part 4)

    - by Geertjan
    The next step is to activate the undo/redo functionality... for a Node. Something I've not seen done before. I.e., when the Node is renamed via F2 on the Node, the "Undo/Redo" buttons should start working. Here is the start of the solution, via this item in the mailing list and Timon Veenstra's BeanNode class, note especially the items in bold: public class ShipNode extends BeanNode implements PropertyChangeListener, UndoRedo.Provider { private final InstanceContent ic; private final ShipSaveCapability saveCookie; private UndoRedo.Manager manager; private String oldDisplayName; private String newDisplayName; private Ship ship; public ShipNode(Ship bean) throws IntrospectionException { this(bean, new InstanceContent()); } private ShipNode(Ship bean, InstanceContent ic) throws IntrospectionException { super(bean, Children.LEAF, new ProxyLookup(new AbstractLookup(ic), Lookups.singleton(bean))); this.ic = ic; setDisplayName(bean.getType()); setShortDescription(String.valueOf(bean.getYear())); saveCookie = new ShipSaveCapability(bean); bean.addPropertyChangeListener(WeakListeners.propertyChange(this, bean)); } @Override public Action[] getActions(boolean context) { List<? extends Action> shipActions = Utilities.actionsForPath("Actions/Ship"); return shipActions.toArray(new Action[shipActions.size()]); } protected void fire(boolean modified) { if (modified) { ic.add(saveCookie); } else { ic.remove(saveCookie); } } @Override public UndoRedo getUndoRedo() { manager = Lookup.getDefault().lookup( UndoRedo.Manager.class); return manager; } private class ShipSaveCapability implements SaveCookie { private final Ship bean; public ShipSaveCapability(Ship bean) { this.bean = bean; } @Override public void save() throws IOException { StatusDisplayer.getDefault().setStatusText("Saving..."); fire(false); } } @Override public boolean canRename() { return true; } @Override public void setName(String newDisplayName) { Ship c = getLookup().lookup(Ship.class); oldDisplayName = c.getType(); c.setType(newDisplayName); fireNameChange(oldDisplayName, newDisplayName); fire(true); fireUndoableEvent("type", ship, oldDisplayName, newDisplayName); } public void fireUndoableEvent(String property, Ship source, Object oldValue, Object newValue) { ReUndoableEdit reUndoableEdit = new ReUndoableEdit( property, source, oldValue, newValue); UndoableEditEvent undoableEditEvent = new UndoableEditEvent( this, reUndoableEdit); manager.undoableEditHappened(undoableEditEvent); } private class ReUndoableEdit extends AbstractUndoableEdit { private Object oldValue; private Object newValue; private Ship source; private String property; public ReUndoableEdit(String property, Ship source, Object oldValue, Object newValue) { super(); this.oldValue = oldValue; this.newValue = newValue; this.source = source; this.property = property; } @Override public void undo() throws CannotUndoException { setName(oldValue.toString()); } @Override public void redo() throws CannotRedoException { setName(newValue.toString()); } } @Override public String getDisplayName() { Ship c = getLookup().lookup(Ship.class); if (null != c.getType()) { return c.getType(); } return super.getDisplayName(); } @Override public String getShortDescription() { Ship c = getLookup().lookup(Ship.class); if (null != String.valueOf(c.getYear())) { return String.valueOf(c.getYear()); } return super.getShortDescription(); } @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("type")) { String oldDisplayName = evt.getOldValue().toString(); String newDisplayName = evt.getNewValue().toString(); fireDisplayNameChange(oldDisplayName, newDisplayName); } else if (evt.getPropertyName().equals("year")) { String oldToolTip = evt.getOldValue().toString(); String newToolTip = evt.getNewValue().toString(); fireShortDescriptionChange(oldToolTip, newToolTip); } fire(true); } } Undo works when rename is done, but Redo never does, because Undo is constantly activated, since it is reactivated whenever there is a name change. And why must the UndoRedoManager be retrieved from the Lookup (it doesn't work otherwise)? Don't get that part of the code either. Help welcome!

    Read the article

  • Returning from method inside a @synchronized block

    - by Michael Waterfall
    I'd just like to know if it's advised to return from a method within a @synchronized block? For example: - (id)test { @synchronized(self) { if (a) return @"A"; else return @"B"; } } As opposed to: - (id)test { NSString *value; @synchronized(self) { if (a) value = @"A"; else value = @"B"; } return value; } This sample is rather simplistic, but sometimes in a complex method it would make things simpler to be able to return from within a @synchronized block.

    Read the article

  • Simple java syncrhonization question

    - by Misha Koshelev
    Dear All: Was wondering, which is correct: Option One class A { public void methodOne() { synchronized(this) { modifyvalue notifyAll() } } public void methodTwo() { while (valuenotmodified) { synchronized(this) { wait() } } } Option Two class A { public void methodOne() { modifyvalue synchronized(this) { notifyAll() } } public void methodTwo() { while (valuenotmodified) { synchronized(this) { wait() } } } and why? Thank you Misha

    Read the article

  • Simple java synchronization question

    - by Misha Koshelev
    I was wondering, which is correct: Option One class A { public void methodOne() { synchronized(this) { modifyvalue notifyAll() } } public void methodTwo() { while (valuenotmodified) { synchronized(this) { wait() } } } Option Two class A { public void methodOne() { modifyvalue synchronized(this) { notifyAll() } } public void methodTwo() { while (valuenotmodified) { synchronized(this) { wait() } } } and why?

    Read the article

  • Java Memory Model: reordering and concurrent locks

    - by Steffen Heil
    Hi The java meomry model mandates that synchronize blocks that synchronize on the same monitor enforce a before-after-realtion on the variables modified within those blocks. Example: // in thread A synchronized( lock ) { x = true; } // in thread B synchronized( lock ) { System.out.println( x ); } In this case it is garanteed that thread B will see x==true as long as thread A already passed that synchronized-block. Now I am in the process to rewrite lots of code to use the more flexible (and said to be faster) locks in java.util.concurrent, especially the ReentrantReadWriteLock. So the example looks like this: // in thread A synchronized( lock ) { lock.writeLock().lock(); x = true; lock.writeLock().unlock(); } // in thread B synchronized( lock ) { lock.readLock().lock(); System.out.println( x ); lock.readLock().unlock(); } However, I have not seen any hints within the memory model specification that such locks also imply the nessessary ordering. Looking into the implementation it seems to rely on the access to volatile variables inside AbstractQueuedSynchronizer (for the sun implementation at least). However this is not part of any specification and moreover access to non-volatile variables is not really condsidered covered by the memory barrier given by these variables, is it? So, here are my questions: Is it safe to assume the same ordering as with the "old" synchronized blocks? Is this documented somewhere? Is accessing any volatile variable a memory barrier for any other variable? Regards, Steffen

    Read the article

  • Good tools for keeping the content in test/staging/live environments synchronized

    - by David Stratton
    I'm looking for recommendations on automated folder synchronization tools to keep the content in our three environments synchronized automatically. Specifically, we have several applications where a user can upload content (via a File Upload page or a similar mechanism), such as images, pdf files, word documents, etc. In the past, we had the user doing this to our live server, and as a result, our test and staging servers had to be manually synchronized. Going forward, we will have them upload content to the staging server, and we would like some software to automatically copy the files off to the test and live servers EITHER on a scheduled basis OR as the files get uploaded. I was planning on writing my own component, and either set it up as a scheduled task, or use a FileSystemWatcher, but it occurred to me that this has probably already been done, and I might be better off with some sort of synchronization tool that already exists. On our web site, there are a limited number of folders that we want to keep synchronized. In these folders, it is an all or nothing - we want to make sure the folders are EXACT duplicates. This should make it fairly straightforward, and I would think that any software that can synchronize folders would be OK, except that we also would like the software to log changes. (This rules out simple BATCH files.) So I'm curious, if you have a similar environment, how did you solve the challenge of keeping everything synchronized. Are you aware of a tool that is reliable, and will meet our needs? If not, do you have a recommendation for something that will come close, or better yet, an open source solution where we can get the code and modify it as needed? (preferably .NET). Added Also, I DID google this first, but there are so many options, I am interested mostly in knowing what actually works well vs what they SAY works, which is why I'm asking here.

    Read the article

  • synchronized block in JSP tag class

    - by Sudhakar
    Hi, I am trying to find answer for the following ,for the past couple of days ,but couldnt find comprehensive answer Problem Statement I have a custom JSP tag class which handles a web form submission ,captures data and write it to same file in the filesystem. As all web applications,this can be triggeredsimultaneosly ,and i fear that multiple threads would be in action handling each of the submission (we all know thats how Servlet works.) CODE synchronized (this){ final String reportFileName = "testReport.csv"; File reportDir = new File( rootCsDirectory, "reports" ); if(!reportDir.isDirectory())reportDir.mkdir(); File reportFile = new File (reportDir, reportFileName); logReport(reportFile,reportContent.toString()); } ISSUE: - A File object can be opened by one thread for writing and at same time another thread might try to access and fail and throw an exception So i thought of synchronizing (on the object ) should solve the issue , but read some where that jsp engine would have pool of jsp tag objects, so i am afraid that synchronized (this) wont work and it should be changed to synchronized (this.getClass())

    Read the article

  • Adding synchronized lyrics to songs

    - by adopilot
    I want to start something like a personal TuneWiki on my computer. I'm using Windows and have a lot of MP3s. Now I want to add lyrics to them for personal use. I tried Windows Media Player but it is bit a hard to synchronize all of the text with the song time. Are there other tools or players for adding lyrics so that when I start to play a song the streaming text will be synchronized with the beat?

    Read the article

  • objective-c : @synchronized how it works ?

    - by g.revolution
    Hi, i have two methods -(void) a { @synchronized(self) { // critical section 1 } } -(void) b { @synchronized(self) { // critical section 2 } } now my question is if a thread is in critical section 1. will the critical section 2 be locked for other threads or other threads can access critical section 2.

    Read the article

  • Why wait should always be in synchronized block

    - by diy
    Hi gents, We all know that in order to invoke Object.wait() , this call must be placed in synchronized block,otherwise,IllegalMonitorStateException is thrown.But what's the reason for making this restriction?I know that wait() releases the monitor, but why do we need to explicitly acquire the monitor by making particular block synchronized and then release the monitor by calling wait() ? What is the potential damage if it was possible to invoke wait() outside synch block, retaining it's semantics - suspending the caller thread ? Thanks in advance

    Read the article

  • Java synchronized seems ignored

    - by viraptor
    Hi, I've got the following code, which I expected to deadlock after printing out "Main: pre-sync". But it looks like synchronized doesn't do what I expect it to. What happens here? import java.util.*; public class deadtest { public static class waiter implements Runnable { Object obj; public waiter(Object obj) { this.obj = obj; } public void run() { System.err.println("Thead: pre-sync"); synchronized(obj) { System.err.println("Thead: pre-wait"); try { obj.wait(); } catch (Exception e) { } System.err.println("Thead: post-wait"); } System.err.println("Thead: post-sync"); } } public static void main(String args[]) { Object obj = new Object(); System.err.println("Main: pre-spawn"); Thread waiterThread = new Thread(new waiter(obj)); waiterThread.start(); try { Thread.sleep(1000); } catch (Exception e) { } System.err.println("Main: pre-sync"); synchronized(obj) { System.err.println("Main: pre-notify"); obj.notify(); System.err.println("Main: post-notify"); } System.err.println("Main: post-sync"); try { waiterThread.join(); } catch (Exception e) { } } } Since both threads synchronize on the created object, I expected the threads to actually block each other. Currently, the code happily notifies the other thread, joins and exits.

    Read the article

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