Search Results

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

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

  • How one could use a live editor

    - by Sathvik
    I was thinking about a live editing environment where code / a source file is synchronized so that, changes made by one user would be carried across to all others editing the file. Something like Google Wave, but for code. Could this kind of an environment be better for the code, as changes are shared instantly? (with revision-control, of course) Has anyone tried (or has had a need for) using a shared environment for code?

    Read the article

  • WS2008 NTP - Using time.windows.com,0x9 - Time always skewed forwards

    - by David
    I have a domain controller configured to use time.windows.com (with 0x09 flags set). I've noticed that frequently the systems' clock is fast - it varies from 10 minutes to even 45 minutes. I always have to keep resetting the system date/time back to what it should be. When I run "w32tm /query /source" it tells me it's using time.windows.com, and obviously I trust Microsoft not to serve incorrect times, but why is my server's clock fast? EDIT: There are a few Time-Service events in the System log: Event ID: 142 Message: The time service has stopped advertising as a time source because the local clock is not synchronized. Event ID: 139 Message: The time service has started advertising as a time source. These two messages appear in pairs every hour or so. Event 142 appears 14 to 16 minutes after 139 appears. Going back a few months, these events appear: Event ID: 35 Message: The time service is now synchronizing the system time with the time source time.windows.com,0x9 (ntp.m|0x9|0.0.0.0:123-65.55.21.21:123). Event ID: 37 Message: The time provider NtpClient is currently receiving valid time data from time.windows.com,0x9 (ntp.m|0x9|0.0.0.0:123-65.55.21.21:123). Event ID: 47 Message: Time Provider NtpClient: No valid response has been received from manually configured peer time.windows.com,0x9 after 8 attempts to contact it. This peer will be discarded as a time source and NtpClient will attempt to discover a new peer with this DNS name. The error was: The time sample was rejected because: The peer is not synchronized, or it has been too long since the peer's last synchronization. These three events only appear once in the log, back in October.

    Read the article

  • Convert mp4 video to a format xbox 360 can play

    - by Björn Lindqvist
    Here is a video file my Xbox 360 refuses to play: $ MP4Box -info video.mp4 * Movie Info * Timescale 90000 - Duration 02:18:33.365 Fragmented File no - 2 track(s) File Brand mp42 - version 0 Created: GMT Sat Jul 21 07:08:55 2012 File has root IOD (9 bytes) Scene PL 0xff - Graphics PL 0xff - OD PL 0xff Visual PL: ISO Reserved Profile (0x7f) Audio PL: High Quality Audio Profile @ Level 2 (0x0f) No streams included in root OD iTunes Info: Encoder Software: HandBrake 0.9.6 2012022800 Track # 1 Info - TrackID 1 - TimeScale 90000 - Duration 02:18:33.235 Media Info: Language "Undetermined" - Type "vide:avc1" - 199318 samples Visual Track layout: x=0 y=0 width=1280 height=688 MPEG-4 Config: Visual Stream - ObjectTypeIndication 0x21 AVC/H264 Video - Visual Size 1280 x 688 AVC Info: 1 SPS - 1 PPS - Profile High @ Level 4.1 NAL Unit length bits: 32 Self-synchronized Track # 2 Info - TrackID 2 - TimeScale 48000 - Duration 02:18:33.365 Media Info: Language "English" - Type "soun:mp4a" - 389689 samples MPEG-4 Config: Audio Stream - ObjectTypeIndication 0x40 MPEG-4 Audio MPEG-4 Audio AAC LC - 6 Channel(s) - SampleRate 48000 Synchronized on stream 1 $ avconv -i video.mp4 avconv version 0.8.4-4:0.8.4-0ubuntu0.12.04.1, Copyright (c) 2000-2012 the Libav developers built on Nov 6 2012 16:51:33 with gcc 4.6.3 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video.mp4': Metadata: major_brand : mp42 minor_version : 0 compatible_brands: mp42isomavc1 creation_time : 2012-07-21 07:08:55 encoder : HandBrake 0.9.6 2012022800 Duration: 02:18:33.36, start: 0.000000, bitrate: 2299 kb/s Stream #0.0(und): Video: h264 (High), yuv420p, 1280x688, 1973 kb/s, 23.98 fps, 90k tbr, 90k tbn, 180k tbc Metadata: creation_time : 2012-07-21 07:08:55 Stream #0.1(eng): Audio: aac, 48000 Hz, 5.1, s16, 319 kb/s Metadata: creation_time : 2012-07-21 07:08:55 At least one output file must be specified What tool, such as ffmpeg or mencoder, and what magic command line incantation should I use to transcode this file into a format Xbox 360 can play? I want the transcode process to retain as good video quality as possible.

    Read the article

  • Google Chrome sync: limit for bookmarks & extensions?

    - by Lyubomyr Shaydariv
    Actually, Chrome is my favorite web-browser, and one of its most powerful features is synchronizing the actual data into a Google account. For the last years I gained a lot of bookmarks and from time to time browse the extensions gallery to find new valuable ones. Really, synchronizing between my work and home PC's freed me from manual sync. And for the recent months I experience strange glitches. I guess it may be caused by a lot of stored bookmarks (potentially about 3K [in estimate], but please don't ask why :)) and extensions (about 130 installed but only 10-15 daily used). I can mention the following strange things: Recently added bookmarks sometimes are not synchronized (e.g. I put a bookmark at work, but it's not guaranteed I can see it that evening), despite about:sync indicates a good sync process. Sometimes recently modified bookmarks appear in either (let's call) last at home or last at work bookmark folders. Sometimes bookmarks are not synced at all. (Moreover, Chromium versions may even crash) Extensions are not synced now at all. Perhaps, there's another reason, but Google Mail Checker and Google Reader Notifier do not show indicators of incoming e-mails and news. ... I'm not sure but it looks like I might exceed Chrome internal sync limits... Is it right? Are there any workarounds, or should I make a massive bookmarks/extensions cleanup (I really don't want it :()? I mostly use Google Chrome Canary builds, and the my current one is 12.0.732.0. Thanks in advance. Update #1 (2001-04-19): I removed about 50 extensions that I'm not interested in (or that I consider as trash), and gained pretty some results: The extensions count is below 100 (exactly 97); The chrome://extensions page does not get slow (or even frozen) any more on enabling/disabling/uninstalling extensions; The extensions are seem to be synchronized now again.

    Read the article

  • Synchronize two directories on linux pc

    - by Gab
    I need a distributed filesystem (or a synchronization tool) that is capable of keeping a directory synchronized across 4 pc. My requirements are: offline access (data must be available offline on each pc) preserve execution rights: some files are marked executable on a linux partition. This flag should be replicated. efficient sync strategy: some of my files are 20GB, they are changed quite often, but in very little parts (Virtualbox images). Delta transmissions are welcome. efficient handling of space: no history for files, files shouldn't be copied to temp directories "just in case you break it". it must propagate deletions of files modification can happen in any of the 4 pcs, they should be propagated when other pc are connected. Other specs of my solution are: Sync is over a lan, the total amount of data to be synced is around 180GB, in some ten thousand files. Changes are small, but can happen in big files. At the moment i'm interested in a linux only solution. conflicts either don't happen or are solved with "last one wins" I haven't found any good solution. I've been trying: unison: it is the only one working at the moment, but during the hashing phase it hangs my pc for some minute, disk light steady on. Sparkleshare doesn't handle large files nicely. It keeps an history of all your changes that grows up indefinitely. They promise it will be fixed in next releases, but at the moment it still doesn't fit my needs. owncloud (keeps history of each file i change) coda ? (help! i couldn't set it up correctly!) git-annex assistant transforms all your files in symlinks and mark the original file as read only ("just in case you make a mistake while you modify it"!). Before you edit a file you have to issue a special command "git-annex unlock", that creates a local copy of the file, and you have to remember to lock it again if you want it synchronized. What to try next?

    Read the article

  • I/O between AIR client using Native process and executable java .jar

    - by aseem behl
    I am using Adobe AIR 2.0 native process API to launch a java executable jar. I/O is handled by writing to the input stream of the java process and reading from the output stream. The application is event based where several events are fired from the server. We catch these events in java code, handle them and write the output to the outputstream using the synchronized static method below. public class ReaderWriter { static Logger logger = Logger.getLogger(ReaderWriter.class); public synchronized static void writeToAir(String output){ try{ byte[] byteArray = output.getBytes(); DataOutputStream dataOutputStream = new DataOutputStream(System.out); dataOutputStream.write(byteArray); dataOutputStream.flush(); } catch (IOException e) { logger.info("Exception while writing the output. " + e); } } } The issue is that some messages are lost between the transfer and not all messages reach the AIR client. If I run the java application from the console I am receiving all the messages. It would be great if somebody could point out what I am missing. Following are some of the listeners used to send the event data to the AIR client. // class used to process Shutdown events from the Session private class SessionShutdownListener implements SessionListener{ public void onEvent(Event e) { Session.Shutdown sd = (Session.Shutdown) e; Session.ShutdownReason sr = sd.getReason(); String eventOutput = "eo;" + "Session Shutdown event ocurred reason=" + sr.strValue() + "\n"; ReaderWriter.writeToAir(eventOutput); } } // class used to process OperationSucceeded events from the Session private class SessionOperationSucceededListener implements SessionListener{ public void onEvent(Event e) { Session.OperationSucceeded os = (Session.OperationSucceeded) e; String eventOutput = "eo;" + "Session OperationSucceeded event ocurred" + "\n"; ReaderWriter.writeToAir(eventOutput); } }

    Read the article

  • Synchronizing ASP.NET MVC action methods with ReaderWriterLockSlim

    - by James D
    Any obvious issues/problems/gotchas with synchronizing access (in an ASP.NET MVC blogging engine) to a shared object model (NHibernate, but it could be anything) at the Controller/Action level via ReaderWriterLockSlim? (Assume the object model is very large and expensive to build per-request, so we need to share it among requests.) Here's how a typical "Read Post" action would look. Enter the read lock, do some work, exit the read lock. public ActionResult ReadPost(int id) { // ReaderWriterLockSlim allows multiple concurrent writes; this method // only blocks in the unlikely event that some other client is currently // writing to the model, which would only happen if a comment were being // submitted or a new post were being saved. _lock.EnterReadLock(); try { // Access the model, fetch the post with specificied id // Pseudocode, etc. Post p = TheObjectModel.GetPostByID(id); ActionResult ar = View(p); return ar; } finally { // Under all code paths, we must release the read lock _lock.ExitReadLock(); } } Meanwhile, if a user submits a comment or an author authors a new post, they're going to need write access to the model, which is done roughly like so: [AcceptVerbs(HttpVerbs.Post)] public ActionResult SaveComment(/* some posted data */) { // try/finally omitted for brevity _lock.EnterWriteLock(); // Save the comment to the DB, update the model to include the comment, etc. _lock.ExitWriteLock(); } Of course, this could also be done by tagging those action methods with some sort of "synchronized" attribute... but however you do it, my question is is this a bad idea? ps. ReaderWriterLockSlim is optimized for multiple concurrent reads, and only blocks if the write lock is held. Since writes are so infrequent (1000s or 10,000s or 100,000s of reads for every 1 write), and since they're of such a short duration, the effect is that the model is synchronized , and almost nobody ever locks, and if they do, it's not for very long.

    Read the article

  • How do you save images to a Blackberry device via HttpConnection?

    - by Kai
    My script fetches xml via httpConnection and saves to persistent store. No problems there. Then I loop through the saved data to compose a list of image url's to fetch via queue. Each of these requests calls the httpConnection thread as so ... public synchronized void run() { HttpConnection connection = (HttpConnection)Connector.open("http://www.somedomain.com/image1.jpg"); connection.setRequestMethod("GET"); String contentType = connection.getHeaderField("Content-type"); InputStream responseData = connection.openInputStream(); connection.close(); outputFinal(responseData, contentType); } public synchronized void outputFinal(InputStream result, String contentType) throws SAXException, ParserConfigurationException, IOException { if(contentType.startsWith("text/")) { // bunch of xml save code that works fine } else if(contentType.equals("image/png") || contentType.equals("image/jpeg") || contentType.equals("image/gif")) { // how to save images here? } else { //default } } What I can't find any good documentation on is how one would take the response data and save it to an image stored on the device. Maybe I just overlooked something very obvious. Any help is very appreciated. Thanks

    Read the article

  • notify listener inside or outside inner synchronization

    - by Jary Zeels
    Hello all, I am struggling with a decision. I am writing a thread-safe library/API. Listeners can be registered, so the client is notified when something interesting happens. Which of the two implementations is most common? class MyModule { protected Listener listener; protected void somethingHappens() { synchronized(this) { ... do useful stuff ... listener.notify(); } } } or class MyModule { protected Listener listener; protected void somethingHappens() { Listener l = null; synchronized(this) { ... do useful stuff ... l = listener; } l.notify(); } } In the first implementation, the listener is notified inside the synchronization. In the second implementation, this is done outside the synchronization. I feel that the second one is advised, as it makes less room for potential deadlocks. But I am having trouble to convince myself. A downside of the second imlementation is that the client might receive 'incorrect' notifications, which happens if it accessed the module prior to the l.notify() statement. thanks a lot

    Read the article

  • How does this code break the Law of Demeter?

    - by Dave Jarvis
    The following code breaks the Law of Demeter: public class Student extends Person { private Grades grades; public Student() { } /** Must never return null; throw an appropriately named exception, instead. */ private synchronized Grades getGrades() throws GradesException { if( this.grades == null ) { this.grades = createGrades(); } return this.grades; } /** Create a new instance of grades for this student. */ protected Grades createGrades() throws GradesException { // Reads the grades from the database, if needed. // return new Grades(); } /** Answers if this student was graded by a teacher with the given name. */ public boolean isTeacher( int year, String name ) throws GradesException, TeacherException { // The method only knows about Teacher instances. // return getTeacher( year ).nameEquals( name ); } private Grades getGradesForYear( int year ) throws GradesException { // The method only knows about Grades instances. // return getGrades().getForYear( year ); } private Teacher getTeacher( int year ) throws GradesException, TeacherException { // This method knows about Grades and Teacher instances. A mistake? // return getGradesForYear( year ).getTeacher(); } } public class Teacher extends Person { public Teacher() { } /** * This method will take into consideration first name, * last name, middle initial, case sensitivity, and * eventually it could answer true to wild cards and * regular expressions. */ public boolean nameEquals( String name ) { return getName().equalsIgnoreCase( name ); } /** Never returns null. */ private synchronized String getName() { if( this.name == null ) { this.name == ""; } return this.name; } } Questions How is the LoD broken? Where is the code breaking the LoD? How should the code be written to uphold the LoD?

    Read the article

  • How do I update blackberry UI items from a thread?

    - by Andrei T. Ursan
    public class PlayText extends Thread { private int duration; private String text; private PlayerScreen playerscrn; public PlayText(String text, int duration) { this.duration = duration; this.text = text; this.playerscrn = (PlayerScreen)UiApplication.getUiApplication().getActiveScreen(); } public void run() { synchronized(UiApplication.getEventLock()) { try{ RichTextField text1player = new RichTextField(this.text, Field.NON_FOCUSABLE); playerscrn.add(text1player); playerscrn.invalidate(); Thread.sleep(this.duration); RichTextField text2player = new RichTextField("hahhaha", Field.NON_FOCUSABLE); playerscrn.add(text2player); playerscrn.invalidate(); Thread.sleep(1000); RichTextField text3player = new RichTextField("Done", Field.NON_FOCUSABLE); playerscrn.add(text3player); playerscrn.invalidate(); }catch(Exception e){ System.out.println("I HAVE AN ERROR"); } } } } With the above code I'm trying to create a small text player. Instead to get all the text labels one by one, something like display text1player wait this.duration milliseconds display text2player wait 1000 milliseconds display text3player thread done. The screens waits this.duration + 1000 milliseconds and displays all the labels at once. I tried with a runnable and calling .invokeLater or .invokeAndWait but I still get the same behavior, and even if I get dirty like above using synchronized it still doesn't work. Does anyone know how I can display each label at a time? Thank you!

    Read the article

  • Understanding Java Wait and Notify methods

    - by Maddy
    Hello all: I have a following program: import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class SimpleWaitNotify implements Runnable { final static Object obj = new Object(); static boolean value = true; public synchronized void flag() { System.out.println("Before Wait"); try { obj.wait(); } catch (InterruptedException e) { System.out.println("Thread interrupted"); } System.out.println("After Being Notified"); } public synchronized void unflag() { System.out.println("Before Notify All"); obj.notifyAll(); System.out.println("After Notify All Method Call"); } public void run() { if (value) { flag(); } else { unflag(); } } public static void main(String[] args) throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(4); SimpleWaitNotify sWait = new SimpleWaitNotify(); pool.execute(sWait); SimpleWaitNotify.value = false; SimpleWaitNotify sNotify = new SimpleWaitNotify(); pool.execute(sNotify); pool.shutdown(); } } When I wait on obj, I get the following exception Exception in thread "pool-1-thread-1" java.lang.IllegalMonitorStateException: current thread not owner for each of the two threads. But if I use SimpleWaitNotify's monitor then the program execution is suspended. In other words, I think it suspends current execution thread and in turn the executor. Any help towards understanding what's going on would be duly appreciated. This is an area1 where the theory and javadoc seem straightforward, and since there aren't many examples, conceptually left a big gap in me.

    Read the article

  • database schema eligible for delta synchronization

    - by WilliamLou
    it's a question for discussion only. Right now, I need to re-design a mysql database table. Basically, this table contains all the contract records I synchronized from another database. The contract record can be modified, deleted or users can add new contract records via GUI interface. At this stage, the table structure is exactly the same as the Contract info (column: serial number, expiry date etc.). In that case, I can only synchronize the whole table (delete all old records, replace with new ones). If I want to delta(only synchronize with modified, new, deleted records) synchronize the table, how should I change the database schema? here is the method I come up with, but I need your suggestions because I think it's a common scenario in database applications. 1)introduce a sequence number concept/column: for each sequence, mark the new added records, modified records, deleted records with this sequence number. By recording the last synchronized sequence number, only pass those records with higher sequence number; 2) because deleted contracts can be added back, and the original table has primary key constraints, should I create another table for those deleted records? or add a flag column to indicate if this contract has been deleted? I hope I explain my question clearly. Anyway, if you know any articles or your own suggestions about this, please let me know. Thanks!

    Read the article

  • Java: Implement own message queue (threadsafe)

    - by derMax
    The task is to implement my own messagequeue that is thread safe. My approach: public class MessageQueue { /** * Number of strings (messages) that can be stored in the queue. */ private int capacity; /** * The queue itself, all incoming messages are stored in here. */ private Vector<String> queue = new Vector<String>(capacity); /** * Constructor, initializes the queue. * * @param capacity The number of messages allowed in the queue. */ public MessageQueue(int capacity) { this.capacity = capacity; } /** * Adds a new message to the queue. If the queue is full, it waits until a message is released. * * @param message */ public synchronized void send(String message) { //TODO check } /** * Receives a new message and removes it from the queue. * * @return */ public synchronized String receive() { //TODO check return "0"; } } If the queue is empty and I call remove(), I want to call wait() so that another thread can use the send() method. Respectively, I have to call notifyAll() after every iteration. Question: Is that possible? I mean does it work that when I say wait() in one method of an object, that I can then execute another method of the same object? And another question: Does that seem to be clever?

    Read the article

  • java and threads: very strange behaviour

    - by Derk
    private synchronized Map<Team, StandingRow> calculateStanding() { System.out.println("Calculate standing for group " + getName()); Map<Team, StandingRow> standing = new LinkedHashMap<Team, StandingRow>(); for (Team team : teams) { standing.put(team, new StandingRow(team)); } StandingRow homeTeamRow, awayTeamRow; for (Match match : matches.values()) { homeTeamRow = standing.get(match.getHomeTeam()); awayTeamRow = standing.get(match.getAwayTeam()); System.out.println("Contains key for " + match.getHomeTeam() + ": " + standing.containsKey(match.getHomeTeam())); System.out.println("Contains key for " + match.getAwayTeam() + ": " + standing.containsKey(match.getAwayTeam())); } } This is my code. matches contains 6 elements, but the problem is that after two matches no keys are anymore found in the standing map. The output is for example Contains key for Zuid-Afrika: true Contains key for Mexico: true Contains key for Uruguay: true Contains key for Frankrijk: true Contains key for Zuid-Afrika: false Contains key for Uruguay: false Contains key for Frankrijk: false Contains key for Mexico: false Contains key for Mexico: false Contains key for Uruguay: false Contains key for Frankrijk: false Contains key for Zuid-Afrika: false This is in a threaded environment, but the method is synchronized so I thought that this would not give a problem? I have also a simple unit test for this method and that works well.

    Read the article

  • how to restart a Thread?

    - by wizztjh
    It is a RMI Server object , so many sethumanActivity() might be run , how do i make sure the previous changeToFalse thread will be stop or halt before the new changeToFalse run? t. interrupt ? Basically when sethumanActivity() is invoke , the humanActivity will be set to true , but a thread will be run to set it back to false. But I am thinking for how to disable or kill the thread when another sethumanActivity() invoked? public class VitaminDEngine implements VitaminD { public boolean humanActivity = false; changeToFalse cf = new changeToFalse(); Thread t = new Thread(cf); private class changeToFalse implements Runnable{ @Override public void run() { try { Thread.sleep(4000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } humanActivity = false; } } @Override public void sethumanActivity() throws RemoteException { // TODO Auto-generated method stub humanActivity = true; t.start(); } public boolean gethumanActivity() throws RemoteException { // TODO Auto-generated method stub return humanActivity; } } Edited after the help of SOer package smartOfficeJava; import java.rmi.RemoteException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class VitaminDEngine implements VitaminD { public volatile boolean humanActivity = false; changeToFalse cf = new changeToFalse(); ExecutorService service = Executors.newSingleThreadExecutor(); private class changeToFalse implements Runnable{ @Override public void run() { try { Thread.sleep(4000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } humanActivity = false; } } @Override public synchronized void sethumanActivity() throws RemoteException { humanActivity = true; service.submit(cf); } public synchronized boolean gethumanActivity() throws RemoteException { return humanActivity; } }

    Read the article

  • jQuery dynamic css loading weired behavior

    - by jimpsr
    The app I am working on requires dynamic loading of css and js, right now the solution is as follows: myapp.loadCss = function(css){ $("head").append("<link>"); cssDom = $("head").children(":last"); cssDom.attr({rel: "stylesheet", type: "text/css", href: css }); } myapp.loadJs = funciton(js){ ... //$.ajax call is used in synchronized mode to make sure the js is fully loaded } } When some widgets need to be load, the usual call with be myapp.loadCss('/widgets/widget1/css/example.css'); myapp.loadJs('/wiggets/widget1/js/example.js'); The weired thing is that once a while (1 out of 10 or 20), the newly created dom elements from example.js will not be able to get its css from example.css, it seems however my loadCss method does not load the css in a synchronized mode? I have tried to replace my loadCss with the the following code: myapp.loadCss(css){ $('<link href="' + css + '" rel="stylesheet" type="text/css" />').appendTo($('head')); } It seems to be OK then (I refreshed the webpage a hundred times for verification :-( ) But unfortunately this method failed in IE(IE7, not tested in IE6, 8) Is there any better solution for this?

    Read the article

  • Accessing global variable in multithreaded Tomcat server

    - by jwegan
    I have a singleton object that I construct like thus: private static volatile KeyMapper mapper = null; public static KeyMapper getMapper() { if(mapper == null) { synchronized(Utils.class) { if(mapper == null) { mapper = new LocalMemoryMapper(); } } } return mapper; } The class KeyMapper is basically a synchronized wrapper to HashMap with only two functions, one to add a mapping and one to remove a mapping. When running in Tomcat 6.24 on my 32bit Windows machine everything works fine. However when running on a 64 bit Linux machine (CentOS 5.4 with OpenJDK 1.6.0-b09) I add one mapping and print out the size of the HashMap used by KeyMapper to verify the mapping got added (i.e. verify size = 1). Then I try to retrieve the mapping with another request and I keep getting null and when I checked the size of the HashMap it was 0. I'm confident the mapping isn't accidentally being removed since I've commented out all calls to remove (and I don't use clear or any other mutators, just get and put). The requests are going through Tomcat 6.24 (configured to use 200 threads with a minimum of 4 threads) and I passed -Xnoclassgc to the jvm to ensure the class isn't inadvertently getting garbage collected (jvm is also running in -server mode). I also added a finalize method to KeyMapper to print to stderr if it ever gets garbage collected to verify that it wasn't being garbage collected. I'm at my wits end and I can't figure out why one minute the entry in HashMap is there and the next it isn't :(

    Read the article

  • Strange problem with simple multithreading program in Java

    - by Elizabeth
    Hello, I am just starting play with multithreading programming. I would like to my program show alternately character '-' and '+' but it doesn't. My task is to use synchronized keyword. As far I have: class FunnyStringGenerator{ private char c; public FunnyStringGenerator(){ c = '-'; } public synchronized char next(){ if(c == '-'){ c = '+'; } else{ c = '-'; } return c; } } class ThreadToGenerateStr implements Runnable{ FunnyStringGenerator gen; public ThreadToGenerateStr(FunnyStringGenerator fsg){ gen = fsg; } @Override public void run() { for(int i = 0; i < 10; i++){ System.out.print(gen.next()); } } } public class Main{ public static void main(String[] args) throws IOException { FunnyStringGenerator FSG = new FunnyStringGenerator(); ExecutorService exec = Executors.newCachedThreadPool(); for(int i = 0; i < 20; i++){ exec.execute(new ThreadToGenerateStr(FSG)); } } } EDIT: I also testing Thread.sleep in run method instead for loop.

    Read the article

  • Is there any point in using a volatile long?

    - by Adamski
    I occasionally use a volatile instance variable in cases where I have two threads reading from / writing to it and don't want the overhead (or potential deadlock risk) of taking out a lock; for example a timer thread periodically updating an int ID that is exposed as a getter on some class: public class MyClass { private volatile int id; public MyClass() { ScheduledExecutorService execService = Executors.newScheduledThreadPool(1); execService.scheduleAtFixedRate(new Runnable() { public void run() { ++id; } }, 0L, 30L, TimeUnit.SECONDS); } public int getId() { return id; } } My question: Given that the JLS only guarantees that 32-bit reads will be atomic is there any point in ever using a volatile long? (i.e. 64-bit). Caveat: Please do not reply saying that using volatile over synchronized is a case of pre-optimisation; I am well aware of how / when to use synchronized but there are cases where volatile is preferable. For example, when defining a Spring bean for use in a single-threaded application I tend to favour volatile instance variables, as there is no guarantee that the Spring context will initialise each bean's properties in the main thread.

    Read the article

  • Concurrency problem with arrays (Java)

    - by Johannes
    For an algorithm I'm working on I tried to develop a blacklisting mechanism that can blacklist arrays in a specific way: If "1, 2, 3" is blacklisted "1, 2, 3, 4, 5" is also considered blacklisted. I'm quite happy with the solution I've come up with so far. But there seem to be some serious problems when I access a blacklist from multiple threads. The method "contains" (see code below) sometimes returns true, even if an array is not blacklisted. This problem does not occur if I only use one thread, so it most likely is a concurrency problem. I've tried adding some synchronization, but it didn't change anything. I also tried some slightly different implementations using java.util.concurrent classes. Any ideas on how to fix this? public class Blacklist { private static final int ARRAY_GROWTH = 10; private final Node root = new Node(); private static class Node{ private volatile Node[] childNodes = new Node[ARRAY_GROWTH]; private volatile boolean blacklisted = false; public void blacklist(){ this.blacklisted = true; this.childNodes = null; } } public void add(final int[] array){ synchronized (root) { Node currentNode = this.root; for(final int edge : array){ if(currentNode.blacklisted) return; else if(currentNode.childNodes.length <= edge) { currentNode.childNodes = Arrays.copyOf(currentNode.childNodes, edge + ARRAY_GROWTH); } if(currentNode.childNodes[edge] == null) { currentNode.childNodes[edge] = new Node(); } currentNode = currentNode.childNodes[edge]; } currentNode.blacklist(); } } public boolean contains(final int[] array){ synchronized (root) { Node currentNode = this.root; for(final int edge : array){ if(currentNode.blacklisted) return true; else if(currentNode.childNodes.length <= edge || currentNode.childNodes[edge] == null) return false; currentNode = currentNode.childNodes[edge]; } return currentNode.blacklisted; } } }

    Read the article

  • Locking database edit by key name

    - by Will Glass
    I need to prevent simultaneous edits to a database field. Users are executing a push operation on a structured data field, so I want to sequence the operations, not simply ignore one edit and take the second. Essentially I want to do synchronized(key name) { push value onto the database field } and set up the synchronized item so that only one operation on "key name" will occur at a time. (note: I'm simplifying, it's not always a simple push). A crude way to do this would be a global synchronization, but that bottlenecks the entire app. All I need to do is sequence two simultaneous writes with the same key, which is rare but annoying occurrence. This is a web-based java app, written with Spring (and using JPA/MySQL). The operation is triggered by a user web service call. (the root cause is when a user sends two simultaneous http requests with the same key). I've glanced through the Doug Lea/Josh Bloch/et al Concurrency in Action, but don't see an obvious solution. Still, this seems simple enough I feel there must be an elegant way to do this.

    Read the article

  • DefaultStyledDocument.styleChanged(Style style) may not run in a timely manner?

    - by Paul Reiners
    I'm experiencing an intermittent problem with a class that extends javax.swing.text.DefaultStyledDocument. This document is being sent to a printer. Most of the time the formatting of the document looks correct, but once in a while it doesn't. It looks like some of the changes in the formatting have not been applied. I took a look at the DefaultStyledDocument.styleChanged(Style style) code: /** * Called when any of this document's styles have changed. * Subclasses may wish to be intelligent about what gets damaged. * * @param style The Style that has changed. */ protected void styleChanged(Style style) { // Only propagate change updated if have content if (getLength() != 0) { // lazily create a ChangeUpdateRunnable if (updateRunnable == null) { updateRunnable = new ChangeUpdateRunnable(); } // We may get a whole batch of these at once, so only // queue the runnable if it is not already pending synchronized(updateRunnable) { if (!updateRunnable.isPending) { SwingUtilities.invokeLater(updateRunnable); updateRunnable.isPending = true; } } } } /** * When run this creates a change event for the complete document * and fires it. */ class ChangeUpdateRunnable implements Runnable { boolean isPending = false; public void run() { synchronized(this) { isPending = false; } try { writeLock(); DefaultDocumentEvent dde = new DefaultDocumentEvent(0, getLength(), DocumentEvent.EventType.CHANGE); dde.end(); fireChangedUpdate(dde); } finally { writeUnlock(); } } } Does the fact that SwingUtilities.invokeLater(updateRunnable) is called, rather than invokeAndWait(updateRunnable), mean that I can't count on my formatting changes appearing in the document before it is rendered? If that is the case, is there a way to ensure that I don't proceed with rendering until the updates have occurred?

    Read the article

  • Can a Java HashMap's size() be out of sync with its actual entries' size ?

    - by trix
    I have a Java HashMap called statusCountMap. Calling size() results in 30. But if I count the entries manually, it's 31 This is in one of my TestNG unit tests. These results below are from Eclipse's Display window (type code - highlight - hit Display Result of Evaluating Selected Text). statusCountMap.size() (int) 30 statusCountMap.keySet().size() (int) 30 statusCountMap.values().size() (int) 30 statusCountMap (java.util.HashMap) {40534-INACTIVE=2, 40526-INACTIVE=1, 40528-INACTIVE=1, 40492-INACTIVE=3, 40492-TOTAL=4, 40513-TOTAL=6, 40532-DRAFT=4, 40524-TOTAL=7, 40526-DRAFT=2, 40528-ACTIVE=1, 40524-DRAFT=2, 40515-ACTIVE=1, 40513-DRAFT=4, 40534-DRAFT=1, 40514-TOTAL=3, 40529-DRAFT=4, 40515-TOTAL=3, 40492-ACTIVE=1, 40528-TOTAL=4, 40514-DRAFT=2, 40526-TOTAL=3, 40524-INACTIVE=2, 40515-DRAFT=2, 40514-ACTIVE=1, 40534-TOTAL=3, 40513-ACTIVE=2, 40528-DRAFT=2, 40532-TOTAL=4, 40524-ACTIVE=3, 40529-ACTIVE=1, 40529-TOTAL=5} statusCountMap.entrySet().size() (int) 30 What gives ? Anyone has experienced this ? I'm pretty sure statusCountMap is not being modified at this point. There are 2 methods (lets call them methodA and methodB) that modify statusCountMap concurrently, by repeatedly calling incrementCountInMap. private void incrementCountInMap(Map map, Long id, String qualifier) { String key = id + "-" + qualifier; if (map.get(key) == null) { map.put(key, 0); } synchronized (map) { map.put(key, map.get(key).intValue() + 1); } } methodD is where I'm getting the issue. methodD has a TestNG @dependsOnMethods = { "methodA", "methodB" } so when methodD is executing, statusCountMap is pretty much static already. I'm mentioning this because it might be a bug in TestNG. I'm using Sun JDK 1.6.0_24. TestNG is testng-5.9-jdk15.jar Hmmm ... after rereading my post, could it be because of concurrent execution of outside-of-synchronized-block map.get(key) == null & map.put(key,0) that's causing this issue ?

    Read the article

  • Synchronize write to two collections

    - by glaz666
    I need to put some value to maps if it is not there yet. The key-value (if set) should always be in two collections (that is put should happen in two maps atomically). I have tried to implement this as follows: private final ConcurrentMap<String, Object> map1 = new ConcurrentHashMap<String, Object>(); private final ConcurrentMap<String, Object> map2 = new ConcurrentHashMap<String, Object>(); public Object putIfAbsent(String key) { Object retval = map1.get(key); if (retval == null) { synchronized (map1) { retval = map1.get(key); if (retval == null) { Object value = new Object(); //or get it somewhere synchronized (map2) { map1.put(key, value); map2.put(key, new Object()); } retval = value; } } } return retval; } public void doSomething(String key) { Object obj1 = map1.get(key); Object obj2 = map2.get(key); //do smth } Will that work fine in all cases? Thanks

    Read the article

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