Search Results

Search found 278 results on 12 pages for 'deadlock'.

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

  • Deadlock error in INSERT statement

    - by Gnanam
    We've got a web-based application. There is a time-bound database operation (INSERTs and UPDATEs) in the application which takes more time to complete, hence this particular flow has been changed into Java Thread so it will not wait (block) for the complete database operation to be completed. My problem is, if more than 1 user come across this particular flow, I'm facing the following error thrown by PostgreSQL: org.postgresql.util.PSQLException: ERROR: deadlock detected Detail: Process 13560 waits for ShareLock on transaction 3147316424; blocked by process 13566. Process 13566 waits for ShareLock on transaction 3147316408; blocked by process 13560. Above error is consistently thrown in INSERT statements. Additional Information: 1) I have PRIMARY KEY defined in this table. 2) There are FOREIGN KEY references in this table. 3) Separate database connection is passed to each Java Thread. Technologies Web Server: Tomcat v6.0.10 Java v1.6.0 Servlet Database: PostgreSQL v8.2.3 Connection Management: pgpool II

    Read the article

  • Indy10 Deadlock at TCPServer

    - by user1769184
    to write information on the processing state to the GUI inside a tcpserver.onexecute(..) function , i used the following command sequence ExecuteDUMMYCommand(Global_Send_Record); BitMap_PaintImageProcess; TThread.Synchronize(nil, BitMap_PaintImageProcess); The code is working well on some machines, but on a few it fails. The code execution stops atTThread.Synchronize command. I guess on these machines the function call is trapped inside a deadlock Any chance to figure out the real problem behind ? The procedure BitMap_PaintImageProcess , here I create a Bitmap and do a lot of painting stuff , but is seems that this code is never executed ?

    Read the article

  • TransactionScope Prematurely Completed

    - by Chris
    I have a block of code that runs within a TransactionScope and within this block of code I make several calls to the DB. Selects, Updates, Creates, and Deletes, the whole gamut. When I execute my delete I execute it using an extension method of the SqlCommand that will automatically resubmit the query if it deadlocks as this query could potentially hit a deadlock. I believe the problem occurs when a deadlock is hit and the function tries to resubmit the query. This is the error I receive: The transaction associated with the current connection has completed but has not been disposed. The transaction must be disposed before the connection can be used to execute SQL statements. This is the simple code that executes the query (all of the code below executes within the using of the TransactionScope): using (sqlCommand.Connection = new SqlConnection(ConnectionStrings.App)) { sqlCommand.Connection.Open(); sqlCommand.ExecuteNonQueryWithDeadlockHandling(); } Here is the extension method that resubmits the deadlocked query: public static class SqlCommandExtender { private const int DEADLOCK_ERROR = 1205; private const int MAXIMUM_DEADLOCK_RETRIES = 5; private const int SLEEP_INCREMENT = 100; public static void ExecuteNonQueryWithDeadlockHandling(this SqlCommand sqlCommand) { int count = 0; SqlException deadlockException = null; do { if (count > 0) Thread.Sleep(count * SLEEP_INCREMENT); deadlockException = ExecuteNonQuery(sqlCommand); count++; } while (deadlockException != null && count < MAXIMUM_DEADLOCK_RETRIES); if (deadlockException != null) throw deadlockException; } private static SqlException ExecuteNonQuery(SqlCommand sqlCommand) { try { sqlCommand.ExecuteNonQuery(); } catch (SqlException exception) { if (exception.Number == DEADLOCK_ERROR) return exception; throw; } return null; } } The error occurs on the line that executes the nonquery: sqlCommand.ExecuteNonQuery();

    Read the article

  • Implementing deadlock condition

    - by Bhaskar
    I am trying to implementing deadlock condition but somehow I am not able to get it working. Both the threads Thread1 and Thread2 are entering in the run function but only one of them enters in Sub/Sum depending on who entered run first. Example : if Thread2 entered run first the it will call sub() and Thread1 never calls sum(). I have also added sleep time so that Thread2 sleeps before calling sum() and Thread1 gets enough time to enter Sum() but Thread1 never enters. public class ExploringThreads { public static void main(String[] args) { // TODO Auto-generated method stub threadexample a1 = new threadexample(); Thread t1 = new Thread(a1, "Thread1"); Thread t2 = new Thread(a1,"Thread2"); t1.start(); t2.start(); } } class threadexample implements Runnable{ public int a = 10; public void run(){ if(Thread.currentThread().getName().equals("Thread1")) sum(); else if(Thread.currentThread().getName().equals("Thread2")) sub(); } public synchronized void sum() { try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"In Sum"); sub(); } public synchronized void sub() { try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"In Sub"); sum(); } }

    Read the article

  • Problem with waveOutWrite and waveOutGetPosition deadlock

    - by MusiGenesis
    I'm working on an app that plays audio continuously using the waveOut... API from winmm.dll. The app uses "leapfrog" buffers, which are basically a bunch of arrays of samples that you dump into the audio queue. Windows plays them seamlessly in sequence, and as each buffer completes Windows calls a callback function. Inside this function, I load the next set of samples into the buffer, process them however, and then dump the buffer back into the audio queue. In this way, the audio plays indefinitely. For animation purposes, I'm trying to incorporate waveOutGetPosition into the application (since the "buffer done" callbacks are irregular enough to cause jerky animation). waveOutGetPosition returns the current position of playback, so it's hyper-precise. The problem is that in my application, making calls to waveOutGetPosition eventually causes the application to lock up - the sound stops and the call never returns. I've boiled things down to a simple app that demonstrates the problem. You can run the app here: http://www.musigenesis.com/SO/waveOut%20demo.exe If you just hear a tiny bit of piano over and over, it's working. It's just meant to demonstrate the problem. The source code for this project is here: http://www.musigenesis.com/SO/WaveOutDemo.zip The first button runs the app in leapfrog mode without making the calls to waveOutGetPosition. If you click this, the app will play forever without breaking (the X button will close it and shut it off). The second button starts the leapfrogger and also starts a forms timer that calls the waveOutGetPosition and displays the current position. Click this and the app will run for a short while and then lock up. On my laptop, it usually locks up in 15-30 seconds; at most it's taken a minute. I have no idea how to fix this, so any help or suggestions would be most welcome. I've found very few posts on this issue, but it seems that there is a potential deadlock, either from multiple calls to waveOutGetPosition or from calls to that and waveOutWrite that occur at the same time. It's possible that I'm calling this too frequently for the system to handle.

    Read the article

  • Python: Script works, but seems to deadlock after some time

    - by sberry2A
    I have the following script, which is working for the most part Link to PasteBin The script's job is to start a number of threads which in turn each start a subprocess with Popen. The output from each subprocess is as follows: 1 2 3 . . . n Done Bascially the subprocess is transferring 10M records from tables in one database to different tables in another db with a lot of data massaging/manipulation in between because of the different schemas. If the subprocess fails at any time in it's execution (bad records, duplicate primary keys, etc), or it completes successfully, it will output "Done\n". If there are no more records to select against for transfer then it will output "NO DATA\n" My intent was to create my script "tableTransfer.py" which would spawn a number of these processes, read their output, and in turn output information such as number of updates completed, time remaining, time elapsed, and number of transfers per second. I started running the process last night and checked in this morning to see it had deadlocked. There were not subprocceses running, there are still records to be updated, and the script had not exited. It was simply sitting there, no longer outputting the current information because no subprocces were running to update the total number complete which is what controls updates to the output. This is running on OS X. I am looking for three things: I would like to get rid of the possibility of this deadlock occurring so I don't need to check in on it as frequently. Is there some issue with locking? Am I doing this in a bad way (gThreading variable to control looping of spawning additional thread... etc.) I would appreciate some suggestions for improving my overall methodology. How should I handle ctrl-c exit? Right now I need to kill the process, but assume I should be able to use the signal module or other to catch the signal and kill the threads, is that right? I am not sure whether I should be pasting my entire script here, since I usually just paste snippets. Let me know if I should paste it here as well.

    Read the article

  • Postgresql: Implicit lock acquisition from foreign-key constraint evaluation

    - by fennec
    So, I'm being confused about foreign key constraint handling in Postgresql. (version 8.4.4, for what it's worth). We've got a couple of tables, mildly anonymized below: device: (id, blah, blah, blah, blah, blah x 50)… primary key on id whooooole bunch of other junk device_foo: (id, device_id, left, right) Foreign key (device_id) references device(id) on delete cascade; primary key on id btree index on 'left' and 'right' So I set out with two database windows to run some queries. db1> begin; lock table device in exclusive mode; db2> begin; update device_foo set left = left + 1; The db2 connection blocks. It seems odd to me that an update of the 'left' column on device_stuff should be affected by activity on the device table. But it is. In fact, if I go back to db1: db1> select * from device_stuff for update; *** deadlock occurs *** The pgsql log has the following: blah blah blah deadlock blah. CONTEXT: SQL statement "SELECT 1 FROM ONLY "public"."device" x WHERE "id" OPERATOR(pg_catalog.=) $1 FOR SHARE OF X: update device_foo set left = left + 1; I suppose I've got two issues: the first is that I don't understand the precise mechanism by which this sort of locking occurs. I have got a couple of useful queries to query pg_locks to see what sort of locks a statement invokes, but I haven't been able to observe this particular sort of locking when I run the update device_foo command in isolation. (Perhaps I'm doing something wrong, though.) I also can't find any documentation on the lock acquisition behavior of foreign-key constraint checks. All I have is a log message. Am I to infer from this that any change to a row will acquire an update lock on all the tables which it's foreign-keyed against? The second issue is that I'd like to find some way to make it not happen like that. I'm ending up with occasional deadlocks in the actual application. I'd like to be able to run big update statements that impact all rows on device_foo without acquiring a big lock on the device table. (There's a lot of access going on in the device table, and it's kind of an expensive lock to get.)

    Read the article

  • Killing a deadlocked Task in .NET 4 TPL

    - by Dan Bryant
    I'd like to start using the Task Parallel Library, as this is the recommended framework going forward for performing asynchronous operations. One thing I haven't been able to find is any means of forcible Abort, such as what Thread.Abort provides. My particular concern is that I schedule tasks running code that I don't wish to completely trust. In particular, I can't be sure this untrusted code won't deadlock and therefore I can't be certain if a Task I schedule using this code will ever complete. I want to stay away from true AppDomain isolation (due to the overhead and complexity of marshaling), but I also don't want to leave a Task thread hanging around, deadlocked. Is there a way to do this in TPL?

    Read the article

  • How to start coding the "Dining Philosophers" simulation?

    - by GrizzlyGuru
    I'm not a beginner at C# but I really need to increase my understanding, so I've picked a classic deadlock problem to code to help teach myself some of the more advanced concepts of C#. The Dining Philosophers Problem seems like a good one, but I need a little help to get started. I know I need to approach the "diners" as objects, but to simulate the random delays between eating, should I look to threading with each diner in a separate thread? Do I need some kind of "master" to monitor all the actions? Any general design concept advice is welcome, but I'd like to do the grunt programming as an exercise. Thanks!

    Read the article

  • Getting deadlocks in MySQL

    - by at
    We're very frustratingly getting deadlocks in MySQL. It isn't because of exceeding a lock timeout as the deadlocks happen instantly when they do happen. Here's the SQL code that is executing on 2 separate threads (with 2 separate connections from the connection pool) that produces a deadlock: UPDATE Sequences SET Counter = LAST_INSERT_ID(Counter + 1) WHERE Sequence IS NULL Sequences table has 2 columns: Sequence and Counter The LAST_INSERT_ID allows us to retrieve this updated counter value as per MySQL's recommendation. That works perfect for us, but we get these deadlocks! Why are we getting them and how can we avoid them?? Thanks so much for any help with this.

    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

  • How can I get the main thread to sleep while waiting for a delgate to be called?

    - by Erik B
    Consider a class with these methods: - (id) initWithFrame: (CGRect) frame { if (!(self = [super init])) return nil; webView = [[UIWebView alloc] initWithFrame:frame]; [webView setDelegate:self]; lock = [[NSConditionLock alloc] initWithCondition:LOCK_WAIT]; return self; } - (void) setHTML: (NSString *) html { [lock lockWhenCondition:LOCK_WAIT]; [webView loadHTMLString:html baseURL:nil]; [lock unlock]; } - (void)webViewDidFinishLoad:(UIWebView *)aWebView { [lock lockWhenCondition:LOCK_WAIT]; // Locking to be able to unlock and change the condition. [lock unlockWithCondition:LOCK_GO]; } - (NSString *) stringByEvaluatingJavaScriptFromString: (NSString *) jsCommand { [lock lockWhenCondition:LOCK_GO]; return [webView stringByEvaluatingJavaScriptFromString:jsCommand]; [lock unlock]; } Let's call this class SynchronousUIWebView. From the main thread I execute: webView = [[SynchronousUIWebView alloc] initWithFrame:frame]; [webView setHTML:html]; [webView stringByEvaluatingJavaScriptFromString:jsCommand]; The problem seems to be that the delegate is not called until I leave the current call stack, which I don't since I'm waiting for the delegate call to happen, aka deadlock. To me it seems like the delegate call is pushed to a queue that is called when the current call is done. So the question is can I modify this behavior? Note: The reason this is needed is that I can't execute the JavaScript until the HTML has loaded.

    Read the article

  • problem with implementing a simple work queue

    - by John Deerikio
    Hi all, I am having troubles with implementing a simple work queue. Doing some analysis, I am facing a subtle problem. The work queue is backed by a regular linked list. The code looks like this (simplified): 0. while (true) 1. while (enabled == true) 2. acquire lock on the list and get the next action to be executed (blocking operation) (store it in a local variable) 3. execute the action (outside the lock on the list on previous line) 4. get lock on this work queue 5. wait until this work queue has been notified (triggered when setEnabled(true) has been callled) The setEnabled(e) operation looks like this (simplified): enabled = e if (enabled == true) acquire lock on this work queue and do notify() Although this works, there is a condition in which a deadlock occurs. It happens in the following rare situation: while an action is being executed, setEnabled(false) is called just before step (4) is entered, setEnabled(true) is called now step (5) keeps waiting forever, because this work queue has already been notified How do I solve this? I have been looking at this for some time, but I cannot come up with a solution. Please note I am fairly new to thread synchronization. Thanks a lot.

    Read the article

  • SQL Server race condition issue with range lock

    - by Freek
    I'm implementing a queue in SQL Server (please no discussions about this) and am running into a race condition issue. The T-SQL of interest is the following: set transaction isolation level serializable begin tran declare @RecordId int declare @CurrentTS datetime2 set @CurrentTS=CURRENT_TIMESTAMP select top 1 @RecordId=Id from QueuedImportJobs with (updlock) where Status=@Status and (LeaseTimeout is null or @CurrentTS>LeaseTimeout) order by Id asc if @@ROWCOUNT> 0 begin update QueuedImportJobs set LeaseTimeout = DATEADD(mi,5,@CurrentTS), LeaseTicket=newid() where Id=@RecordId select * from QueuedImportJobs where Id = @RecordId end commit tran RecordId is the PK and there is also an index on Status,LeaseTimeout. What I'm basically doing is select a record of which the lease happens to be expired, while simultaneously updating the lease time with 5 minutes and setting a new lease ticket. So the problem is that I'm getting deadlocks when I run this code in parallel using a couple of threads. I've debugged it up to the point where I found out that the update statement sometimes gets executing twice for the same record. Now, I was under the impression that the with (updlock) should prevent this (it also happens with xlock btw, not with tablockx). So it actually look like there is a RangeS-U and a RangeX-X lock on the same range of records, which ought to be impossible. So what am I missing? I'm thinking it might have something to do with the top 1 clause or that SQL Server does not know that where Id=@RecordId is actually in the locked range? Deadlock graph: Table schema (simplified):

    Read the article

  • Small openmp programm freezes sometimes (gcc, c, linux)

    - by osgx
    Hello Just write a small omp test, and it does not work correctly all the times: #include <omp.h> int main() { int i,j=0; #pragma omp parallel for(i=0;i<1000;i++) { #pragma omp barrier j+= j^i; } return j; } The usage of j for writing from all threads is incorrect in this example, BUT there must be only nondeterministic value of j I have a freeze. Compiled with gcc-4.3.1 -fopenmp a.c -o gcc -static Run on 4-core x86_Core2 Linux server: $ ./gcc and got freeze (sometimes; like 1 freeze for 4-5 fast runs). Strace: [pid 13118] <... futex resumed> ) = 0 [pid 13118] futex(0x80d3014, FUTEX_WAIT, 2, NULL <unfinished ...> [pid 13120] <... futex resumed> ) = 0 [pid 13119] futex(0x80d3014, FUTEX_WAIT, 2, NULL <unfinished ...> [pid 13120] futex(0x80d3014, FUTEX_WAKE, 1) = 1 [pid 13120] futex(0x80cd798, FUTEX_WAIT, 1, NULL <unfinished ...> [pid 13109] <... futex resumed> ) = 0 [pid 13109] futex(0x80d3014, FUTEX_WAKE, 1) = 1 [pid 13109] futex(0x80d3020, FUTEX_WAIT, 251, NULL <unfinished ...> [pid 13118] <... futex resumed> ) = 0 [pid 13118] futex(0x80d3014, FUTEX_WAKE, 1) = 1 [pid 13119] <... futex resumed> ) = 0 [pid 13118] futex(0x80d3020, FUTEX_WAIT, 251, NULL <unfinished ...> [pid 13119] futex(0x80d3014, FUTEX_WAKE, 1) = 0 [pid 13119] futex(0x80d3020, FUTEX_WAIT, 251, NULL <freeze> Why do I have a freeze (deadlock)?

    Read the article

  • WCF deadlock when using callback channel

    - by mafutrct
    This is probably a simple mistake, but I could not figure out what was wrong. I basically got a method like this: [ServiceBehavior ( ConcurrencyMode = ConcurrencyMode.Reentrant, InstanceContextMode = InstanceContextMode.PerSession, IncludeExceptionDetailInFaults = true) ] public class Impl : SomeContract { public string Foo() { _CallbackChannel.Blah(); return ""; } } Its interface is decorated: [ServiceContract ( Namespace = "http://MyServiceInterface", SessionMode = SessionMode.Required, CallbackContract = typeof (WcfCallbackContract)) ] public interface SomeContract { [OperationContract] string Foo (); } The service is hosted like this: ServiceHost host = new ServiceHost (typeof (Impl)); var binding = new NetTcpBinding (); var address = new Uri ("net.tcp://localhost:8000/"); host.AddServiceEndpoint ( typeof (SomeContract), binding, address); host.Open (); The client implements the callback interface and calls Foo. Foo runs, calls the callback method and returns. However, the client is still struck in the call to Foo and never returns. The client callback method is never run. I guess I made a design mistake somewhere. If needed, I can post more code. Any help is appreciated.

    Read the article

  • catching a deadlock in a simple odd-even sending

    - by user562264
    I'm trying to solve a simple problem with MPI, my implementation is MPICH2 and my code is in fortran. I have used the blocking send and receive, the idea is so simple but when I run it it crashes!!! I have absolutely no idea what is wrong? can anyone make quote on this issue please? there is a piece of the code: integer,parameter::IM=100,JM=100 REAL,ALLOCATABLE ::T(:,:),TF(:,:) CALL MPI_COMM_RANK(MPI_COMM_WORLD,RNK,IERR) CALL MPI_COMM_SIZE(MPI_COMM_WORLD,SIZ,IERR) prv = rnk-1 nxt = rnk+1 LIM = INT(IM/SIZ) IF (rnk==0) THEN ALLOCATE(TF(IM,JM)) prv = MPI_PROC_NULL ELSEIF(rnk==siz-1) THEN NXT = MPI_PROC_NULL LIM = LIM+MOD(IM,SIZ) END IF IF (MOD(RNK,2)==0) THEN CALL MPI_SEND(T(2,:),JM+2,MPI_REAL,PRV,10,MPI_COMM_WORLD,IERR) CALL MPI_RECV(T(1,:),JM+2,MPI_REAL,PRV,20,MPI_COMM_WORLD,STAT,IERR) ELSE CALL MPI_RECV(T(LIM+2,:),JM+2,MPI_REAL,NXT,10,MPI_COMM_WORLD,STAT,IERR) CALL MPI_SEND(T(LIM+1,:),JM+2,MPI_REAL,NXT,20,MPI_COMM_WORLD,IERR) END IF as I understood even processes are not receiving anything while the odd ones finish sending successfully, in some cases when I added some print to observe what is going on I saw that the variable NXT is changing during the sending procedure!!! for example all the odd process was sending message to process 0 not their next one!

    Read the article

  • MySql Query lag time / deadlock?

    - by Click Upvote
    When there are multiple PHP scripts running in parallel, each making an UPDATE query to the same record in the same table repeatedly, is it possible for there to be a 'lag time' before the table is updated with each query? I have basically 5-6 instances of a PHP script running in parallel, having been launched via cron. Each script gets all the records in the items table, and then loops through them and processes them. However, to avoid processing the same item more than once, I store the id of the last item being processed in a seperate table. So this is how my code works: function getCurrentItem() { $sql = "SELECT currentItemId from settings"; $result = $this->db->query($sql); return $result->get('currentItemId'); } function setCurrentItem($id) { $sql = "UPDATE settings SET currentItemId='$id'"; $this->db->query($sql); } $currentItem = $this->getCurrentItem(); $sql = "SELECT * FROM items WHERE status='pending' AND id > $currentItem'"; $result = $this->db->query($sql); $items = $result->getAll(); foreach ($items as $i) { //Check if $i has been processed by a different instance of the script, and if so, //leave it untouched. if ($this->getCurrentItem() > $i->id) continue; $this->setCurrentItem($i->id); // Process the item here } But despite of all the precautions, most items are being processed more than once. Which makes me think that there is some lag time between the update queries being run by the PHP script, and when the database actually updates the record. Is it true? And if so, what other mechanism should I use to ensure that the PHP scripts always get only the latest currentItemId even when there are multiple scripts running in parrallel? Would using a text file instead of the db help?

    Read the article

  • Deadlock in ThreadPoolExecutor

    - by Vitaly
    Encountered a situation when ThreadPoolExecutor is parked in execute(Runnable) function while all the ThreadPool threads are waiting in getTask func, workQueue is empty. Does anybody have any ideas? The ThreadPoolExecutor is created with ArrayBlockingQueue, corePoolSize == maximumPoolSize = 4 [Edit] To be more precise, the thread is blocked in ThreadPoolExecutor.exec(Runnable command) func. It has the task to execute, but doesn't do it. [Edit2] The executor is blocked somewhere inside the working queue (ArrayBlockingQueue). [Edit3] The callstack: thread = front_end(224) at sun.misc.Unsafe.park(Native methord) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158) at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:747) at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireQueued(AbstractQueuedSynchronizer.java:778) at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer.java:1114) at java.util.concurrent.locks.ReentrantLock$NonfairSync.lock(ReentrantLock.java:186) at java.util.concurrent.locks.ReentrantLock.lock(ReentrantLock.java:262) at java.util.concurrent.ArrayBlockingQueue.offer(ArrayBlockingQueue.java:224) at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:653) at net.listenThread.WorkersPool.execute(WorkersPool.java:45) at the same time the workQueue is empty (checked using remote debug) [Edit4] Code working with ThreadPoolExecutor: public WorkersPool(int size) { pool = new ThreadPoolExecutor(size, size, IDLE_WORKER_THREAD_TIMEOUT, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(WORK_QUEUE_CAPACITY), new ThreadFactory() { @NotNull private final AtomicInteger threadsCount = new AtomicInteger(0); @NotNull public Thread newThread(@NotNull Runnable r) { final Thread thread = new Thread(r); thread.setName("net_worker_" + threadsCount.incrementAndGet()); return thread; } }, new RejectedExecutionHandler() { public void rejectedExecution(@Nullable Runnable r, @Nullable ThreadPoolExecutor executor) { Verify.warning("new task " + r + " is discarded"); } }); } public void execute(@NotNull Runnable task) { pool.execute(task); } public void stopWorkers() throws WorkersTerminationFailedException { pool.shutdownNow(); try { pool.awaitTermination(THREAD_TERMINATION_WAIT_TIME, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new WorkersTerminationFailedException("Workers-pool termination failed", e); } } }

    Read the article

  • deadlock when using WCF Duplex Polling with Silverlight

    - by Kobi Hari
    Hi all. I have followed Tomek Janczuk's demonstration on silverlight tv to create a chat program that uses WCF Duplex Polling web service. The client subscribes to the server, and then the server initiates notifications to all connected clients to publish events. The Idea is simple, on the client, there is a button that allows the client to connect. A text box where the client can write a message and publish it, and a bigger text box that presents all the notifications received from the server. I connected 3 clients (in different browsers - IE, Firefox and Chrome) and it all works nicely. They send messages and receive them smoothly. The problem starts when I close one of the browsers. As soon as one client is out, the other clients get stuck. They stop getting notifications. I am guessing that the loop in the server that goes through all the clients and sends them the notifications is stuck on the client that is now missing. I tried catching the exception and removing it from the clients list (see code) but it still does not help. any ideas? The server code is as follows: using System; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Activation; using System.Collections.Generic; using System.Runtime.Remoting.Channels; namespace ChatDemo.Web { [ServiceContract] public interface IChatNotification { // this will be used as a callback method, therefore it must be one way [OperationContract(IsOneWay=true)] void Notify(string message); [OperationContract(IsOneWay = true)] void Subscribed(); } // define this as a callback contract - to allow push [ServiceContract(Namespace="", CallbackContract=typeof(IChatNotification))] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class ChatService { SynchronizedCollection<IChatNotification> clients = new SynchronizedCollection<IChatNotification>(); [OperationContract(IsOneWay=true)] public void Subscribe() { IChatNotification cli = OperationContext.Current.GetCallbackChannel<IChatNotification>(); this.clients.Add(cli); // inform the client it is now subscribed cli.Subscribed(); Publish("New Client Connected: " + cli.GetHashCode()); } [OperationContract(IsOneWay = true)] public void Publish(string message) { SynchronizedCollection<IChatNotification> toRemove = new SynchronizedCollection<IChatNotification>(); foreach (IChatNotification channel in this.clients) { try { channel.Notify(message); } catch { toRemove.Add(channel); } } // now remove all the dead channels foreach (IChatNotification chnl in toRemove) { this.clients.Remove(chnl); } } } } The client code is as follows: void client_NotifyReceived(object sender, ChatServiceProxy.NotifyReceivedEventArgs e) { this.Messages.Text += string.Format("{0}\n\n", e.Error != null ? e.Error.ToString() : e.message); } private void MyMessage_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { this.client.PublishAsync(this.MyMessage.Text); this.MyMessage.Text = ""; } } private void Button_Click(object sender, RoutedEventArgs e) { this.client = new ChatServiceProxy.ChatServiceClient(new PollingDuplexHttpBinding { DuplexMode = PollingDuplexMode.MultipleMessagesPerPoll }, new EndpointAddress("../ChatService.svc")); // listen for server events this.client.NotifyReceived += new EventHandler<ChatServiceProxy.NotifyReceivedEventArgs>(client_NotifyReceived); this.client.SubscribedReceived += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_SubscribedReceived); // subscribe for the server events this.client.SubscribeAsync(); } void client_SubscribedReceived(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { try { Messages.Text += "Connected!\n\n"; gsConnect.Color = Colors.Green; } catch { Messages.Text += "Failed to Connect!\n\n"; } } And the web config is as follows: <system.serviceModel> <extensions> <bindingExtensions> <add name="pollingDuplex" type="System.ServiceModel.Configuration.PollingDuplexHttpBindingCollectionElement, System.ServiceModel.PollingDuplex, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> </bindingExtensions> </extensions> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> <bindings> <pollingDuplex> <binding name="myPollingDuplex" duplexMode="MultipleMessagesPerPoll"/> </pollingDuplex> </bindings> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/> <services> <service name="ChatDemo.Web.ChatService"> <endpoint address="" binding="pollingDuplex" bindingConfiguration="myPollingDuplex" contract="ChatDemo.Web.ChatService"/> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> </system.serviceModel>

    Read the article

  • Facebook JS API: users_getInfo() inside ifUserConnected() deadlock.

    - by serg555
    I am trying to put Facebook connect button on the site and once connected display connected username. But for some reason following code goes into some infinite loop during first connection, and then works fine unless I delete this app from my facebook profile which causes freezing again. Here is a code on FB connect button click: FB.Connect.requireSession(); Here is code directly on the page: <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US" type="text/javascript"></script> <script type="text/javascript"> FB.init("123", "/xd_receiver.htm"); FB.ensureInit(function() { FB.Connect.ifUserConnected(function() { FB.Facebook.apiClient.users_getInfo(new Array(FB.Connect.get_loggedInUser()),new Array("name"), function(user, exec) { console.log("logged in:"+user[0].name); }); }, function(){ console.log("guest"); }); }); </script> If I remove FB.Facebook.apiClient.users_getInfo() it works fine, but I need to get username somehow. Any tips? Thanks.

    Read the article

  • My multithread program works slowly or appear deadlock on dual core machine, please help

    - by Shangping Guo
    I have a program with several threads, one thread will change a global when it exits itself and the other thread will repeatedly poll the global. No any protection on the globals. The program works fine on uni-processor. On dual core machine, it works for a while and then halt either on Sleep(0) or SuspendThread(). Would anyone be able to help me out on this? The code would be like this: Thread 1: do something... while(1) { ..... flag_thread1_running=false; SuspendThread(GetCurrentThread()); continue; } Thread 2 .... while(flag_thread1_running==false) Sleep(0); ....

    Read the article

  • Permanent mutex locking causing deadlock?

    - by Daniel
    I am having a problem with mutexes (pthread_mutex on Linux) where if a thread locks a mutex right again after unlocking it, another thread is not very successful getting a lock. I've attached test code where one mutex is created, along with two threads that in an endless loop lock the mutex, sleep for a while and unlock it again. The output I expect to see is "alive" messages from both threads, one from each (e.g. 121212121212. However what I get is that one threads gets the majority of locks (e.g. 111111222222222111111111 or just 1111111111111...). If I add a usleep(1) after the unlocking, everything works as expected. Apparently when the thread goes to SLEEP the other thread gets its lock - however this is not the way I was expecting it, as the other thread has already called pthread_mutex_lock. I suspect this is the way this is implemented, in that the actice thread has priority, however it causes certain problem in this particular testcase. Is there any way to prevent it (short of adding a deliberately large enough delay or some kind of signaling) or where is my error in understanding? #include <pthread.h> #include <stdio.h> #include <string.h> #include <sys/time.h> #include <unistd.h> pthread_mutex_t mutex; void* threadFunction(void *id) { int count=0; while(true) { pthread_mutex_lock(&mutex); usleep(50*1000); pthread_mutex_unlock(&mutex); // usleep(1); ++count; if (count % 10 == 0) { printf("Thread %d alive\n", *(int*)id); count = 0; } } return 0; } int main() { // create one mutex pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutex_init(&mutex, &attr); // create two threads pthread_t thread1; pthread_t thread2; pthread_attr_t attributes; pthread_attr_init(&attributes); int id1 = 1, id2 = 2; pthread_create(&thread1, &attributes, &threadFunction, &id1); pthread_create(&thread2, &attributes, &threadFunction, &id2); pthread_attr_destroy(&attributes); sleep(1000); return 0; }

    Read the article

  • Is READ UNCOMMITTED / NOLOCK safe in this situation?

    - by Ben Challenor
    I know that snapshot isolation would fix this problem, but I'm wondering if NOLOCK is safe in this specific case so that I can avoid the overhead. I have a table that looks something like this: drop table Data create table Data ( Id BIGINT NOT NULL, Date BIGINT NOT NULL, Value BIGINT, constraint Cx primary key (Date, Id) ) create nonclustered index Ix on Data (Id, Date) There are no updates to the table, ever. Deletes can occur but they should never contend with the SELECT because they affect the other, older end of the table. Inserts are regular and page splits to the (Id, Date) index are extremely common. I have a deadlock situation between a standard INSERT and a SELECT that looks like this: select top 1 Date, Value from Data where Id = @p0 order by Date desc because the INSERT acquires a lock on Cx (Date, Id; Value) and then Ix (Id, Date), but the SELECT acquires a lock on Ix (Id, Date) and then Cx (Date, Id; Value). This is because the SELECT first seeks on Ix and then joins to a seek on Cx. Swapping the clustered and non-clustered index would break this cycle, but it is not an acceptable solution because it would introduce cycles with other (more complex) SELECTs. If I add NOLOCK to the SELECT, can it go wrong in this case? Can it return: More than one row, even though I asked for TOP 1? No rows, even though one exists and has been committed? Worst of all, a row that doesn't satisfy the WHERE clause? I've done a lot of reading about this online, but the only reproductions of over- or under-count anomalies I've seen (one, two) involve a scan. This involves only seeks. Jeff Atwood has a post about using NOLOCK that generated a good discussion. I was particularly interested in a comment by Rick Townsend: Secondly, if you read dirty data, the risk you run is of reading the entirely wrong row. For example, if your select reads an index to find your row, then the update changes the location of the rows (e.g.: due to a page split or an update to the clustered index), when your select goes to read the actual data row, it's either no longer there, or a different row altogether! Is this possible with inserts only, and no updates? If so, then I guess even my seeks on an insert-only table could be dangerous. Update: I'm trying to figure out how snapshot isolation works. It seems to be row-based, where transactions read the table (with no shared lock!), find the row they are interested in, and then see if they need to get an old version of the row from the version store in tempdb. But in my case, no row will have more than one version, so the version store seems rather pointless. And if the row was found with no shared lock, how is it different to just using NOLOCK?

    Read the article

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