Search Results

Search found 514 results on 21 pages for 'runnable'.

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

  • SQL SERVER – Single Wait Time Introduction with Simple Example – Wait Type – Day 2 of 28

    - by pinaldave
    In this post, let’s delve a bit more in depth regarding wait stats. The very first question: when do the wait stats occur? Here is the simple answer. When SQL Server is executing any task, and if for any reason it has to wait for resources to execute the task, this wait is recorded by SQL Server with the reason for the delay. Later on we can analyze these wait stats to understand the reason the task was delayed and maybe we can eliminate the wait for SQL Server. It is not always possible to remove the wait type 100%, but there are few suggestions that can help. Before we continue learning about wait types and wait stats, we need to understand three important milestones of the query life-cycle. Running - a query which is being executed on a CPU is called a running query. This query is responsible for CPU time. Runnable – a query which is ready to execute and waiting for its turn to run is called a runnable query. This query is responsible for Single Wait time. (In other words, the query is ready to run but CPU is servicing another query). Suspended – a query which is waiting due to any reason (to know the reason, we are learning wait stats) to be converted to runnable is suspended query. This query is responsible for wait time. (In other words, this is the time we are trying to reduce). In simple words, query execution time is a summation of the query Executing CPU Time (Running) + Query Wait Time (Suspended) + Query Single Wait Time (Runnable). Again, it may be possible a query goes to all these stats multiple times. Let us try to understand the whole thing with a simple analogy of a taxi and a passenger. Two friends, Tom and Danny, go to the mall together. When they leave the mall, they decide to take a taxi. Tom and Danny both stand in the line waiting for their turn to get into the taxi. This is the Signal Wait Time as they are ready to get into the taxi but the taxis are currently serving other customer and they have to wait for their turn. In other word they are in a runnable state. Now when it is their turn to get into the taxi, the taxi driver informs them he does not take credit cards and only cash is accepted. Neither Tom nor Danny have enough cash, they both cannot get into the vehicle. Tom waits outside in the queue and Danny goes to ATM to fetch the cash. During this time the taxi cannot wait, they have to let other passengers get into the taxi. As Tom and Danny both are outside in the queue, this is the Query Wait Time and they are in the suspended state. They cannot do anything till they get the cash. Once Danny gets the cash, they are both standing in the line again, creating one more Single Wait Time. This time when their turn comes they can pay the taxi driver in cash and reach their destination. The time taken for the taxi to get from the mall to the destination is running time (CPU time) and the taxi is running. I hope this analogy is bit clear with the wait stats. You can check the single wait stats using following query of Glenn Berry. -- Signal Waits for instance SELECT CAST(100.0 * SUM(signal_wait_time_ms) / SUM (wait_time_ms) AS NUMERIC(20,2)) AS [%signal (cpu) waits], CAST(100.0 * SUM(wait_time_ms - signal_wait_time_ms) / SUM (wait_time_ms) AS NUMERIC(20,2)) AS [%resource waits] FROM sys.dm_os_wait_stats OPTION (RECOMPILE); Higher the single wait stats are not good for the system. Very high value indicates CPU pressure. In my experience, when systems are running smooth and without any glitch the single wait stat is lower than 20%. Again, this number can be debated (and it is from my experience and is not documented anywhere). In other words, lower is better and higher is not good for the system. In future articles we will discuss in detail the various wait types and wait stats and their resolution. Read all the post in the Wait Types and Queue series. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, PostADay, SQL, SQL Authority, SQL DMV, SQL Performance, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, SQL Wait Stats, SQL Wait Types, T SQL, Technology

    Read the article

  • How to create a thread in XNA for pathfinding?

    - by Dan
    I am trying to create a separate thread for my enemy's A* pathfinder which will give me a list of points to get to the player. I have placed the thread in the update method of my enemy. However this seems to cause jittering in the game every-time the thread is called. I have tried calling just the method and this works fine. Is there any way I can sort this out so that I can have the pathfinder on its own thread? Do I need to remove the thread start from the update and start it in the constructor? Is there any way this can work? Here is the code at the moment: bool running = false; bool threadstarted; System.Threading.Thread thread; public void update() { if (running == false && threadstarted == false) { thread = new System.Threading.Thread(PathThread); //thread.Priority = System.Threading.ThreadPriority.Lowest; thread.IsBackground = true; thread.Start(startandendobj); //PathThread(startandendobj); threadstarted = true; } } public void PathThread(object Startandend) { object[] Startandendarray = (object[])Startandend; Point startpoint = (Point)Startandendarray[0]; Point endpoint = (Point)Startandendarray[1]; bool runnable = true; // Path find from 255, 255 to 0,0 on the map foreach(Tile tile in Map) { if(tile.Color == Color.Red) { if (tile.Position.Contains(endpoint)) { runnable = false; } } } if(runnable == true) { running = true; Pathfinder p = new Pathfinder(Map); pathway = p.FindPath(startpoint, endpoint); running = false; threadstarted = false; } }

    Read the article

  • Create a thread in xna Update method to find path?

    - by Dan
    I am trying to create a separate thread for my enemy's A* pathfinder which will give me a list of points to get to the player. I have placed the thread in the update method of my enemy. However this seems to cause jittering in the game every-time the thread is called. I have tried calling just the method and this works fine. Is there any way I can sort this out so that I can have the pathfinder on its own thread? Do I need to remove the thread start from the update and start it in the constructor? Is there any way this can work. Here is the code at the moment: bool running = false; bool threadstarted; System.Threading.Thread thread; public void update() { if (running == false && threadstarted == false) { thread = new System.Threading.Thread(PathThread); //thread.Priority = System.Threading.ThreadPriority.Lowest; thread.IsBackground = true; thread.Start(startandendobj); //PathThread(startandendobj); threadstarted = true; } } public void PathThread(object Startandend) { object[] Startandendarray = (object[])Startandend; Point startpoint = (Point)Startandendarray[0]; Point endpoint = (Point)Startandendarray[1]; bool runnable = true; // Path find from 255, 255 to 0,0 on the map foreach(Tile tile in Map) { if(tile.Color == Color.Red) { if (tile.Position.Contains(endpoint)) { runnable = false; } } } if(runnable == true) { running = true; Pathfinder p = new Pathfinder(Map); pathway = p.FindPath(startpoint, endpoint); running = false; threadstarted = false; } }

    Read the article

  • Handling commands or events that wait for an action to be completed afterwards

    - by virulent
    Say you have two events: Action1 and Action2. When you receive Action1, you want to store some arbitrary data to be used the next time Action2 rolls around. Optimally, Action1 is normally a command however it can also be other events. The idea is still the same. The current way I am implementing this is by storing state and then simply checking when Action2 is called if that specific state is there. This is obviously a bit messy and leads to a lot of redundant code. Here is an example of how I am doing that, in pseudocode form (and broken down quite a bit, obviously): void onAction1(event) { Player = event.getPlayer() Player.addState("my_action_to_do") } void onAction2(event) { Player = event.getPlayer() if not Player.hasState("my_action_to_do") { return } // Do something } When doing this for a lot of other actions it gets somewhat ugly and I wanted to know if there is something I can do to improve upon it. I was thinking of something like this, which wouldn't require passing data around, but is this also not the right direction? void onAction1(event) { Player = event.getPlayer() Player.onAction2(new Runnable() { public void run() { // Do something } }) } If one wanted to take it even further, could you not simply do this? void onPlayerEnter(event) { // When they join the server Player = event.getPlayer() Player.onAction1(new Runnable() { public void run() { // Now wait for action 2 Player.onAction2(new Runnable() { // Do something }) } }, true) // TRUE would be to repeat the event, // not remove it after it is called. } Any input would be wonderful.

    Read the article

  • is it right to call ejb bean from thread by ThreadPoolExecutor?

    - by kislo_metal
    I trying to call some ejb bean method from tread. and getting error : (as is glassfish v3) Log Level SEVERE Logger javax.enterprise.system.std.com.sun.enterprise.v3.services.impl Name-Value Pairs {_ThreadName=Thread-1, _ThreadID=42} Record Number 928 Message ID java.lang.NullPointerException at ua.co.rufous.server.broker.TempLicService.run(TempLicService.java Complete Message 35) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:637) here is tread public class TempLicService implements Runnable { String hash; //it`s Stateful bean @EJB private LicActivatorLocal lActivator; public TempLicService(String hash) { this.hash= hash; } @Override public void run() { lActivator.proccessActivation(hash); } } my ThreadPoolExecutor public class RequestThreadPoolExecutor extends ThreadPoolExecutor { private boolean isPaused; private ReentrantLock pauseLock = new ReentrantLock(); private Condition unpaused = pauseLock.newCondition(); private static RequestThreadPoolExecutor threadPool; private RequestThreadPoolExecutor() { super(1, Integer.MAX_VALUE, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); System.out.println("RequestThreadPoolExecutor created"); } public static RequestThreadPoolExecutor getInstance() { if (threadPool == null) threadPool = new RequestThreadPoolExecutor(); return threadPool; } public void runService(Runnable task) { threadPool.execute(task); } protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); pauseLock.lock(); try { while (isPaused) unpaused.await(); } catch (InterruptedException ie) { t.interrupt(); } finally { pauseLock.unlock(); } } public void pause() { pauseLock.lock(); try { isPaused = true; } finally { pauseLock.unlock(); } } public void resume() { pauseLock.lock(); try { isPaused = false; unpaused.signalAll(); } finally { pauseLock.unlock(); } } public void shutDown() { threadPool.shutdown(); } //<<<<<< creating thread here public void runByHash(String hash) { Runnable service = new TempLicService(hash); threadPool.runService(service); } } and method where i call it (it is gwt servlet, but there is no proble to call thread that not contain ejb) : @Override public Boolean submitHash(String hash) { System.out.println("submiting hash"); try { if (tBoxService.getTempLicStatus(hash) == 1) { //<<< here is the call RequestThreadPoolExecutor.getInstance().runByHash(hash); return true; } } catch (NoResultException e) { e.printStackTrace(); } return false; } I need to organize some pool of submitting hash to server (calls of LicActivator bean), is ThreadPoolExecutor design good idea and why it is not working in my case? (as I know we can`t create thread inside bean, but could we call bean from different threads? ). If No, what is the bast practice for organize such request pool? Thanks. << Answer: I am using DI (EJB 3.1) soo i do not need any look up here. (application packed in ear and both modules in it (web module and ejb), it works perfect for me). But I can use it only in managed classes. So.. 2.Can I use manual look up in Tread ? Could I use Bean that extends ThreadPoolExecutor and calling another bean that implements Runnable ? Or it is not allowed ?

    Read the article

  • SQL Server IO handling mechanism can be severely affected by high CPU usage

    - by sqlworkshops
    Are you using SSD or SAN / NAS based storage solution and sporadically observe SQL Server experiencing high IO wait times or from time to time your DAS / HDD becomes very slow according to SQL Server statistics? Read on… I need your help to up vote my connect item – https://connect.microsoft.com/SQLServer/feedback/details/744650/sql-server-io-handling-mechanism-can-be-severely-affected-by-high-cpu-usage. Instead of taking few seconds, queries could take minutes/hours to complete when CPU is busy.In SQL Server when a query / request needs to read data that is not in data cache or when the request has to write to disk, like transaction log records, the request / task will queue up the IO operation and wait for it to complete (task in suspended state, this wait time is the resource wait time). When the IO operation is complete, the task will be queued to run on the CPU. If the CPU is busy executing other tasks, this task will wait (task in runnable state) until other tasks in the queue either complete or get suspended due to waits or exhaust their quantum of 4ms (this is the signal wait time, which along with resource wait time will increase the overall wait time). When the CPU becomes free, the task will finally be run on the CPU (task in running state).The signal wait time can be up to 4ms per runnable task, this is by design. So if a CPU has 5 runnable tasks in the queue, then this query after the resource becomes available might wait up to a maximum of 5 X 4ms = 20ms in the runnable state (normally less as other tasks might not use the full quantum).In case the CPU usage is high, let’s say many CPU intensive queries are running on the instance, there is a possibility that the IO operations that are completed at the Hardware and Operating System level are not yet processed by SQL Server, keeping the task in the resource wait state for longer than necessary. In case of an SSD, the IO operation might even complete in less than a millisecond, but it might take SQL Server 100s of milliseconds, for instance, to process the completed IO operation. For example, let’s say you have a user inserting 500 rows in individual transactions. When the transaction log is on an SSD or battery backed up controller that has write cache enabled, all of these inserts will complete in 100 to 200ms. With a CPU intensive parallel query executing across all CPU cores, the same inserts might take minutes to complete. WRITELOG wait time will be very high in this case (both under sys.dm_io_virtual_file_stats and sys.dm_os_wait_stats). In addition you will notice a large number of WAITELOG waits since log records are written by LOG WRITER and hence very high signal_wait_time_ms leading to more query delays. However, Performance Monitor Counter, PhysicalDisk, Avg. Disk sec/Write will report very low latency times.Such delayed IO handling also occurs to read operations with artificially very high PAGEIOLATCH_SH wait time (with number of PAGEIOLATCH_SH waits remaining the same). This problem will manifest more and more as customers start using SSD based storage for SQL Server, since they drive the CPU usage to the limits with faster IOs. We have a few workarounds for specific scenarios, but we think Microsoft should resolve this issue at the product level. We have a connect item open – https://connect.microsoft.com/SQLServer/feedback/details/744650/sql-server-io-handling-mechanism-can-be-severely-affected-by-high-cpu-usage - (with example scripts) to reproduce this behavior, please up vote the item so the issue will be addressed by the SQL Server product team soon.Thanks for your help and best regards,Ramesh MeyyappanHome: www.sqlworkshops.comLinkedIn: http://at.linkedin.com/in/rmeyyappan

    Read the article

  • evaluation of a java thread dump

    - by raticulin
    I got a thread dump of one of my processes. It has a bunch of these threads. I guess they are keeping a bunch of memory so I am getting OOM. "Thread-8264" prio=6 tid=0x4c94ac00 nid=0xf3c runnable [0x4fe7f000] java.lang.Thread.State: RUNNABLE at java.util.zip.Inflater.inflateBytes(Native Method) at java.util.zip.Inflater.inflate(Inflater.java:223) - locked <0x0c9bc640 (a java.util.zip.Inflater) at org.apache.commons.compress.archivers.zip.ZipArchiveInputStream.read(ZipArchiveInputStream.java:235) at com.my.ZipExtractorCommonsCompress.extract(ZipExtractorCommonsCompress.java:48) at com.my.CustomThreadedExtractorWrapper$ExtractionThread.run(CustomThreadedExtractorWrapper.java:151) Locked ownable synchronizers: - None "Thread-8241" prio=6 tid=0x4c94a400 nid=0xb8c runnable [0x4faef000] java.lang.Thread.State: RUNNABLE at java.util.zip.Inflater.inflateBytes(Native Method) at java.util.zip.Inflater.inflate(Inflater.java:223) - locked <0x0c36b808 (a java.util.zip.Inflater) at org.apache.commons.compress.archivers.zip.ZipArchiveInputStream.read(ZipArchiveInputStream.java:235) at com.my.ZipExtractorCommonsCompress.extract(ZipExtractorCommonsCompress.java:48) at com.my.CustomThreadedExtractorWrapper$ExtractionThread.run(CustomThreadedExtractorWrapper.java:151) Locked ownable synchronizers: - None I am trying to find out how it arrived to this situation. CustomThreadedExtractorWrapper is a wrapper class that fires a thread to do some work (ExtractionThread, which uses ZipExtractorCommonsCompress to extract zip contents from a compressed stream). If the task is taking too long, ExtractionThread.interrupt(); is called to cancel the operation. I can see in my logs that the cancellation happened 25 times. And I see 21 of these threads in my dump. My questions: What is the status of these threads? Alive and running? Blocked somehow? They did not die with .interrupt() apparently? Is there a sure way to really kill a thread? What does really mean 'locked ' in the stack trace? Line 223 in Inflater.java is: public synchronized int inflate(byte[] b, int off, int len) { ... //return is line 223 return inflateBytes(b, off, len); }

    Read the article

  • Filling SWT table object using a separated thread class ...

    - by erlord
    Hi all I've got a code snippet by the swt team that does exactly what I need. However, there is a part I want to separate into another class, in particular, the whole inline stuff. In response to my former question, it has been suggested that Callable should be used in order to implement threaded objects. It is suggested to make use of an implementation of runnable or better callable, since I do need some kind of return. However, I don't get it. My problems are: In the original code, within the inline implementation of the method run, some of the parents objects are called. How would I do this when the thread is separated? Pass the object via the C'tor's parameter? In the original code, another runnable object is nested within the runnable implementation. What is it good for? How to implement this when having separated the code? Furthermore, this nested runnable again calls objects created by the main method. Please, have mercy with me, but I am still quite a beginner and my brain is near collapsing :-( All I want is to separate all the threaded stuff into another class and make the program do just the same thing as it already does. Help please! Again thank you very much in advance for any useful suggestions, hints, examples etc... Regs Me

    Read the article

  • Why my object sees variables which were not given to it in the constructor?

    - by Roman
    I have the following code. Which is "correct" and which I do not understand: private static void updateGUI(final int i, final JLabel label) { SwingUtilities.invokeLater( new Runnable() { public void run() { label.setText("You have " + i + " seconds."); } } ); } I create a new instance of the Runnable class and then in the run method of this instance I use variables label and i. It works, but I do not understand why it work. Why the considered object sees values of these variables. According to my understanding the code should look like that (and its wrong): private static void updateGUI(final int i, final JLabel label) { SwingUtilities.invokeLater(new Runnable(i,label) { public Runnable(int i, JLabel label) { this.i = i; this.label = label; } public void run() { label.setText("You have " + i + " seconds."); } }); } So, I would give the i and label variables to the constructor so the object can access them... By the way, in the updateGUI I use final before the i and label. I think I used final because compiler wanted that. But I do not understand why.

    Read the article

  • Threads syncronization with ThreadPoolExecutor

    - by justme1
    I'm trying to implement some logic when I create main(father) thread witch executes several other threads. Then it waits for some condition which child threads creates. After condition is meet the father executes some more child threads. The problem that when I use wait/notify I have java.lang.IllegalMonitorStateException exception. Here is the code: public class MyExecutor { final static ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(10); final static ExecutorService svc = Executors.newFixedThreadPool(1); static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 8, 10, TimeUnit.SECONDS, queue); public static void main(String[] args) throws InterruptedException { final MyExecutor me = new MyExecutor(); svc.execute(new Runnable() { public void run() { try { System.out.println("Main Thread"); me.execute(threadPool, 1); System.out.println("Main Thread waiting"); wait(); System.out.println("Main Thread notified"); me.execute(threadPool, 2); Thread.sleep(100); threadPool.shutdown(); threadPool.awaitTermination(20000, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } }); svc.shutdown(); svc.awaitTermination(10000, TimeUnit.SECONDS); System.out.println("Main Thread finished"); } public void execute(ThreadPoolExecutor tpe, final int id) { tpe.execute(new Runnable() { public void run() { try { System.out.println("Child Thread " + id); Thread.sleep(2000); System.out.println("Child Thread " + id + " finished"); notify(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } } When I comment wait and notify line I have the following output: Main Thread Main Thread waiting Main Thread notified Child Thread 1 Child Thread 2 Child Thread 1 finished Child Thread 2 finished Main Thread finished

    Read the article

  • Why are my thread being terminated ?

    - by Sephy
    Hi, I'm trying to repeat calls to methods through 3 differents threads. But after I start my threads, during the next iteration of my loop, they are all terminated so nothing is executed... The code is as follows : public static void main(String[] args) { main = new Main(); pollingThread.start(); } static Thread pollingThread = new Thread() { @Override public void run() { while (isRunning) { main.poll(); // test the state of the threads try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }; }; public void poll() { if (clientThread == null) { clientThread = new Thread(new Runnable() { @Override public void run() { //create some objects } }); clientThread.start(); } else if (clientThread.isAlive()) { // do some treatment } if (gestionnaireThread == null) { gestionnaireThread = new Thread(new Runnable() { @Override public void run() { //create some objects }; }); gestionnaireThread.start(); } else if (gestionnaireThread.isAlive()) { // do some treatment } if (marchandThread == null) { marchandThread = new Thread(new Runnable() { @Override public void run() { // create some objects }; }); marchandThread.start(); } else if (marchandThread.isAlive()) { // do some treatment } } And for some reason, when I test the state of my different threads, they appear as runnable and then a the 2nd iteration, they are all terminated... What am I doing wrong? I actually have no error, but the threads are terminated and so my loop keeps looping and telling me the threads are terminated.... Thanks for any help.

    Read the article

  • Java ThreadPoolExecutor getting stuck while using ArrayBlockingQueue

    - by Ravi Rao
    Hi, I'm working on some application and using ThreadPoolExecutor for handling various tasks. ThreadPoolExecutor is getting stuck after some duration. To simulate this in a simpler environment, I've written a simple code where I'm able to simulate the issue. import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class MyThreadPoolExecutor { private int poolSize = 10; private int maxPoolSize = 50; private long keepAliveTime = 10; private ThreadPoolExecutor threadPool = null; private final ArrayBlockingQueue&lt;Runnable&gt; queue = new ArrayBlockingQueue&lt;Runnable&gt;( 100000); public MyThreadPoolExecutor() { threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, queue); threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) { System.out .println(&quot;Execution rejected. Please try restarting the application.&quot;); } }); } public void runTask(Runnable task) { threadPool.execute(task); } public void shutDown() { threadPool.shutdownNow(); } public ThreadPoolExecutor getThreadPool() { return threadPool; } public void setThreadPool(ThreadPoolExecutor threadPool) { this.threadPool = threadPool; } public static void main(String[] args) { MyThreadPoolExecutor mtpe = new MyThreadPoolExecutor(); for (int i = 0; i &lt; 1000; i++) { final int j = i; mtpe.runTask(new Runnable() { @Override public void run() { System.out.println(j); } }); } } } Try executing this code a few times. It normally print outs the number on console and when all threads end, it exists. But at times, it finished all task and then is not getting terminated. The thread dump is as follows: MyThreadPoolExecutor [Java Application] MyThreadPoolExecutor at localhost:2619 (Suspended) Daemon System Thread [Attach Listener] (Suspended) Daemon System Thread [Signal Dispatcher] (Suspended) Daemon System Thread [Finalizer] (Suspended) Object.wait(long) line: not available [native method] ReferenceQueue&lt;T&gt;.remove(long) line: not available ReferenceQueue&lt;T&gt;.remove() line: not available Finalizer$FinalizerThread.run() line: not available Daemon System Thread [Reference Handler] (Suspended) Object.wait(long) line: not available [native method] Reference$Lock(Object).wait() line: 485 Reference$ReferenceHandler.run() line: not available Thread [pool-1-thread-1] (Suspended) Unsafe.park(boolean, long) line: not available [native method] LockSupport.park(Object) line: not available AbstractQueuedSynchronizer$ConditionObject.await() line: not available ArrayBlockingQueue&lt;E&gt;.take() line: not available ThreadPoolExecutor.getTask() line: not available ThreadPoolExecutor$Worker.run() line: not available Thread.run() line: not available Thread [pool-1-thread-2] (Suspended) Unsafe.park(boolean, long) line: not available [native method] LockSupport.park(Object) line: not available AbstractQueuedSynchronizer$ConditionObject.await() line: not available ArrayBlockingQueue&lt;E&gt;.take() line: not available ThreadPoolExecutor.getTask() line: not available ThreadPoolExecutor$Worker.run() line: not available Thread.run() line: not available Thread [pool-1-thread-3] (Suspended) Unsafe.park(boolean, long) line: not available [native method] LockSupport.park(Object) line: not available AbstractQueuedSynchronizer$ConditionObject.await() line: not available ArrayBlockingQueue&lt;E&gt;.take() line: not available ThreadPoolExecutor.getTask() line: not available ThreadPoolExecutor$Worker.run() line: not available Thread.run() line: not available Thread [pool-1-thread-4] (Suspended) Unsafe.park(boolean, long) line: not available [native method] LockSupport.park(Object) line: not available AbstractQueuedSynchronizer$ConditionObject.await() line: not available ArrayBlockingQueue&lt;E&gt;.take() line: not available ThreadPoolExecutor.getTask() line: not available ThreadPoolExecutor$Worker.run() line: not available Thread.run() line: not available Thread [pool-1-thread-6] (Suspended) Unsafe.park(boolean, long) line: not available [native method] LockSupport.park(Object) line: not available AbstractQueuedSynchronizer$ConditionObject.await() line: not available ArrayBlockingQueue&lt;E&gt;.take() line: not available ThreadPoolExecutor.getTask() line: not available ThreadPoolExecutor$Worker.run() line: not available Thread.run() line: not available Thread [pool-1-thread-8] (Suspended) Unsafe.park(boolean, long) line: not available [native method] LockSupport.park(Object) line: not available AbstractQueuedSynchronizer$ConditionObject.await() line: not available ArrayBlockingQueue&lt;E&gt;.take() line: not available ThreadPoolExecutor.getTask() line: not available ThreadPoolExecutor$Worker.run() line: not available Thread.run() line: not available Thread [pool-1-thread-5] (Suspended) Unsafe.park(boolean, long) line: not available [native method] LockSupport.park(Object) line: not available AbstractQueuedSynchronizer$ConditionObject.await() line: not available ArrayBlockingQueue&lt;E&gt;.take() line: not available ThreadPoolExecutor.getTask() line: not available ThreadPoolExecutor$Worker.run() line: not available Thread.run() line: not available Thread [pool-1-thread-10] (Suspended) Unsafe.park(boolean, long) line: not available [native method] LockSupport.park(Object) line: not available AbstractQueuedSynchronizer$ConditionObject.await() line: not available ArrayBlockingQueue&lt;E&gt;.take() line: not available ThreadPoolExecutor.getTask() line: not available ThreadPoolExecutor$Worker.run() line: not available Thread.run() line: not available Thread [pool-1-thread-9] (Suspended) Unsafe.park(boolean, long) line: not available [native method] LockSupport.park(Object) line: not available AbstractQueuedSynchronizer$ConditionObject.await() line: not available ArrayBlockingQueue&lt;E&gt;.take() line: not available ThreadPoolExecutor.getTask() line: not available ThreadPoolExecutor$Worker.run() line: not available Thread.run() line: not available Thread [pool-1-thread-7] (Suspended) Unsafe.park(boolean, long) line: not available [native method] LockSupport.park(Object) line: not available AbstractQueuedSynchronizer$ConditionObject.await() line: not available ArrayBlockingQueue&lt;E&gt;.take() line: not available ThreadPoolExecutor.getTask() line: not available ThreadPoolExecutor$Worker.run() line: not available Thread.run() line: not available Thread [DestroyJavaVM] (Suspended) C:\Program Files\Java\jre1.6.0_07\bin\javaw.exe (Jun 17, 2010 10:42:33 AM) In my actual application,ThreadPoolExecutor threads go in this state and then it stops responding. Regards, Ravi Rao

    Read the article

  • ArrayBlockingQueue - How to "interrupt" a thread that is wating on .take() method

    - by bernhard
    I use an ArrayBlockingQueue in my code. Clients will wait untill an element becomes available: myBlockingQueue.take(); How can I "shutdown" my service in case no elements are present in the queue and the take() ist wating indefenitely for an element to become available? This method throws an InterruptedException. My question is, how can I "evoke" an Interrupted Exception so that take() will quit? (I also tought about notify(), but it seems I doesnt help here..) I know I could insert an special "EOF/QUIT" marker Element but is this really the only solution? UPDATE (regarding the comment, that points to another question with two solutions: one mentioned above using a "Poisoning Pill Object" and the second one is Thread.interrupt(): The myBlockingQueue.take() is used NOT in a Thread (extending Thread) but rather implements Runnable. It seems a Runnable does not provide the .interrupt() method? How could I interrupt the Runnable? Million Thanks Bernhard

    Read the article

  • Java: serial thread confinement question

    - by denis
    Assume you have a Collection(ConcurrentLinkedQueue) of Runnables with mutable state. Thread A iterates over the Collection and hands the Runnables to an ExecutorService. The run() method changes the Runnables state. The Runnable has no internal synchronization. The above is a repetitive action and the worker threads need to see the changes made by previous iterations. So a Runnable gets processed by one worker thread after another, but is never accessed by more than one thread at a time - a case of serial thread confinement(i hope ;)). The question: Will it work just with the internal synchronization of the ConcurrentLinkedQueue/ExecutorSerivce? To be more precise: If Thread A hands Runnable R to worker thread B and B changes the state of R, and then A hands R to worker thread C..does C see the modifications done by B?

    Read the article

  • Dispatching generic tasks in WCF or .Net Remoting

    - by Eric
    Hello all, I've been researching for a couple days on and off, and have yet to figure out the best way to achieve the following goal. I would like to define either an interface or abstract class in C# which has an associated Run method, similar to the Java runnable interface. The goal would be to have a shared queue which contains a list of these objects. Then individual clients would be able to derive their own concrete runnable classes and add them to the queue hosted by the server. Clients would also be able to pop these runnable objects off the queue and execute them arbitrarily. This seems like it should be feasible in a VM based language without needing to place any of the concrete implementations in a shared assembly, but I have thus far had no luck finding a working example of such a system. Does anyone know how this might be achieved?

    Read the article

  • Troubleshooting High-CPU Utilization for SQL Server

    - by Susantha Bathige
    The objective of this FAQ is to outline the basic steps in troubleshooting high CPU utilization on  a server hosting a SQL Server instance. The first and the most common step if you suspect high CPU utilization (or are alerted for it) is to login to the physical server and check the Windows Task Manager. The Performance tab will show the high utilization as shown below: Next, we need to determine which process is responsible for the high CPU consumption. The Processes tab of the Task Manager will show this information: Note that to see all processes you should select Show processes from all user. In this case, SQL Server (sqlserver.exe) is consuming 99% of the CPU (a normal benchmark for max CPU utilization is about 50-60%). Next we examine the scheduler data. Scheduler is a component of SQLOS which evenly distributes load amongst CPUs. The query below returns the important columns for CPU troubleshooting. Note – if your server is under severe stress and you are unable to login to SSMS, you can use another machine’s SSMS to login to the server through DAC – Dedicated Administrator Connection (see http://msdn.microsoft.com/en-us/library/ms189595.aspx for details on using DAC) SELECT scheduler_id ,cpu_id ,status ,runnable_tasks_count ,active_workers_count ,load_factor ,yield_count FROM sys.dm_os_schedulers WHERE scheduler_id See below for the BOL definitions for the above columns. scheduler_id – ID of the scheduler. All schedulers that are used to run regular queries have ID numbers less than 1048576. Those schedulers that have IDs greater than or equal to 1048576 are used internally by SQL Server, such as the dedicated administrator connection scheduler. cpu_id – ID of the CPU with which this scheduler is associated. status – Indicates the status of the scheduler. runnable_tasks_count – Number of workers, with tasks assigned to them that are waiting to be scheduled on the runnable queue. active_workers_count – Number of workers that are active. An active worker is never preemptive, must have an associated task, and is either running, runnable, or suspended. current_tasks_count - Number of current tasks that are associated with this scheduler. load_factor – Internal value that indicates the perceived load on this scheduler. yield_count – Internal value that is used to indicate progress on this scheduler.                                                                 Now to interpret the above data. There are four schedulers and each assigned to a different CPU. All the CPUs are ready to accept user queries as they all are ONLINE. There are 294 active tasks in the output as per the current_tasks_count column. This count indicates how many activities currently associated with the schedulers. When a  task is complete, this number is decremented. The 294 is quite a high figure and indicates all four schedulers are extremely busy. When a task is enqueued, the load_factor  value is incremented. This value is used to determine whether a new task should be put on this scheduler or another scheduler. The new task will be allocated to less loaded scheduler by SQLOS. The very high value of this column indicates all the schedulers have a high load. There are 268 runnable tasks which mean all these tasks are assigned a worker and waiting to be scheduled on the runnable queue.   The next step is  to identify which queries are demanding a lot of CPU time. The below query is useful for this purpose (note, in its current form,  it only shows the top 10 records). SELECT TOP 10 st.text  ,st.dbid  ,st.objectid  ,qs.total_worker_time  ,qs.last_worker_time  ,qp.query_plan FROM sys.dm_exec_query_stats qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp ORDER BY qs.total_worker_time DESC This query as total_worker_time as the measure of CPU load and is in descending order of the  total_worker_time to show the most expensive queries and their plans at the top:      Note the BOL definitions for the important columns: total_worker_time - Total amount of CPU time, in microseconds, that was consumed by executions of this plan since it was compiled. last_worker_time - CPU time, in microseconds, that was consumed the last time the plan was executed.   I re-ran the same query again after few seconds and was returned the below output. After few seconds the SP dbo.TestProc1 is shown in fourth place and once again the last_worker_time is the highest. This means the procedure TestProc1 consumes a CPU time continuously each time it executes.      In this case, the primary cause for high CPU utilization was a stored procedure. You can view the execution plan by clicking on query_plan column to investigate why this is causing a high CPU load. I have used SQL Server 2008 (SP1) to test all the queries used in this article.

    Read the article

  • @OnStart & @OnStop

    - by Geertjan
    In applications based on NetBeans Platform 7.2, you'll be able to replace all your ModuleInstall classes with this code: import org.openide.modules.OnStart; import org.openide.modules.OnStop; @OnStart public final class Installer implements Runnable { @Override public void run() { System.out.println("enable something..."); } @OnStop public static final class Down implements Runnable { @Override public void run() { System.out.println("disable something..."); } } } Build the module and the annotations result in named services, thanks to @NamedServiceDefinition: Aside from no longer needing to register the ModuleInstall class in the manifest, performance of startup will be enhanced, if you use the above approach: https://netbeans.org/bugzilla/show_bug.cgi?id=200636

    Read the article

  • How do I handle calls to AudioTrack from jni without crashing?

    - by icecream
    I was trying to write to an AudioTrack from a jni callback, and I get a signal 7 (SIGBUS), fault addr 00000000. I have looked at the Wolf3D example for odroid and they seem to use a android.os.Handler to post a Runnable that will do an update in the correct thread context. I have also tried AttachCurrentThread, but I fail in this case also. It works to play the sound when running from the constructor even if I wrap it in a thread and then post it to the handler. When I do the "same" via a callback from jni it fails. I assume I am braeaking some rules, but I haven't been able to figure out what they are. So far, I haven't found the answer here on SO. So I wonder if anyone knows how this should be done. EDIT: Answered below. The following code is to illustrate the problem. Java: package com.example.jniaudiotrack; import android.app.Activity; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.os.Bundle; import android.os.Handler; import android.util.Log; public class JniAudioTrackActivity extends Activity { AudioTrack mAudioTrack; byte[] mArr; public static final Handler mHandler = new Handler(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mArr = new byte[2048]; for (int i = 0; i < 2048; i++) { mArr[i] = (byte) (Math.sin(i) * 128); } mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT, 2048, AudioTrack.MODE_STREAM); mAudioTrack.play(); new Thread(new Runnable() { public void run() { mHandler.post(new Runnable() { public void run() { mAudioTrack.write(mArr, 0, 2048); Log.i(TAG, "*** Handler from constructor ***"); } }); } }).start(); new Thread(new Runnable() { public void run() { audioFunc(); } }).start(); } public native void audioFunc(); @SuppressWarnings("unused") private void audioCB() { mHandler.post(new Runnable() { public void run() { mAudioTrack.write(mArr, 0, 2048); Log.i(TAG, "*** audioCB called ***"); } }); } private static final String TAG = "JniAudioTrackActivity"; static { System.loadLibrary("jni_audiotrack"); } } cpp: #include <jni.h> extern "C" { JNIEXPORT void Java_com_example_jniaudiotrack_JniAudioTrackActivity_audioFunc(JNIEnv* env, jobject obj); } JNIEXPORT void Java_com_example_jniaudiotrack_JniAudioTrackActivity_audioFunc(JNIEnv* env, jobject obj) { JNIEnv* jniEnv; JavaVM* vm; env->GetJavaVM(&vm); vm->AttachCurrentThread(&jniEnv, 0); jclass cls = env->GetObjectClass(obj); jmethodID audioCBID = env->GetMethodID(cls, "audioCB", "()V"); if (!audioCBID) { return; } env->CallVoidMethod(cls, audioCBID); } Trace snippet: I/DEBUG ( 1653): pid: 9811, tid: 9811 >>> com.example.jniaudiotrack <<< I/DEBUG ( 1653): signal 7 (SIGBUS), fault addr 00000000 I/DEBUG ( 1653): r0 00000800 r1 00000026 r2 00000001 r3 00000000 I/DEBUG ( 1653): r4 42385726 r5 41049e54 r6 bee25570 r7 ad00e540 I/DEBUG ( 1653): r8 000040f8 r9 41048200 10 41049e44 fp 00000000 I/DEBUG ( 1653): ip 000000f8 sp bee25530 lr ad02dbb5 pc ad012358 cpsr 20000010 I/DEBUG ( 1653): #00 pc 00012358 /system/lib/libdvm.so

    Read the article

  • Handling Exceptions for ThreadPoolExecutor

    - by HonorGod
    I have the following code snippet that basically scans through the list of task that needs to be executed and each task is then given to the executor for execution. The JobExecutor intern creates another executor (for doing db stuff...reading and writing data to queue) and completes the task. JobExecutor returns a Future for the tasks submitted. When one of the task fails, I want to gracefully interrupt all the threads and shutdown the executor by catching all the exceptions. What changes do I need to do? public class DataMovingClass { private static final AtomicInteger uniqueId = new AtomicInteger(0); private static final ThreadLocal<Integer> uniqueNumber = new IDGenerator(); ThreadPoolExecutor threadPoolExecutor = null ; private List<Source> sources = new ArrayList<Source>(); private static class IDGenerator extends ThreadLocal<Integer> { @Override public Integer get() { return uniqueId.incrementAndGet(); } } public void init(){ // load sources list } public boolean execute() { boolean succcess = true ; threadPoolExecutor = new ThreadPoolExecutor(10,10, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1024), new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("DataMigration-" + uniqueNumber.get()); return t; }// End method }, new ThreadPoolExecutor.CallerRunsPolicy()); List<Future<Boolean>> result = new ArrayList<Future<Boolean>>(); for (Source source : sources) { result.add(threadPoolExecutor.submit(new JobExecutor(source))); } for (Future<Boolean> jobDone : result) { try { if (!jobDone.get(100000, TimeUnit.SECONDS) && success) { // in case of successful DbWriterClass, we don't need to change // it. success = false; } } catch (Exception ex) { // handle exceptions } } } public class JobExecutor implements Callable<Boolean> { private ThreadPoolExecutor threadPoolExecutor ; Source jobSource ; public SourceJobExecutor(Source source) { this.jobSource = source; threadPoolExecutor = new ThreadPoolExecutor(10,10,10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1024), new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("Job Executor-" + uniqueNumber.get()); return t; }// End method }, new ThreadPoolExecutor.CallerRunsPolicy()); } public Boolean call() throws Exception { boolean status = true ; System.out.println("Starting Job = " + jobSource.getName()); try { // do the specified task ; }catch (InterruptedException intrEx) { logger.warn("InterruptedException", intrEx); status = false ; } catch(Exception e) { logger.fatal("Exception occurred while executing task "+jobSource.getName(),e); status = false ; } System.out.println("Ending Job = " + jobSource.getName()); return status ; } } }

    Read the article

  • java.net.SocketException: Software caused connection abort: socket write error

    - by npinti
    Hi guys, I am trying to send an image from a Java desktop application to a J2ME application. The problem is that I am getting this exception: java.net.SocketException: Software caused connection abort: socket write error I have looked around on the net, and although this problem is not that rare, I was unable to find a concrete solution. I am transforming the image into a byte array before transferring it. These are the methods found on the desktop application and on the J2ME respectively public void send(String ID, byte[] serverMessage) throws Exception { //Get the IP and Port of the person to which the message is to be sent. String[] connectionDetails = this.userDetails.get(ID).split(","); Socket sock = new Socket(InetAddress.getByName(connectionDetails[0]), Integer.parseInt(connectionDetails[1])); OutputStream os = sock.getOutputStream(); for (int i = 0; i < serverMessage.length; i++) { os.write((int) serverMessage[i]); } os.flush(); os.close(); sock.close(); } private void read(final StreamConnection slaveSock) { Runnable runnable = new Runnable() { public void run() { try { DataInputStream dataInputStream = slaveSock.openDataInputStream(); int inputChar; StringBuffer results = new StringBuffer(); while ( (inputChar = dataInputStream.read()) != -1) { results.append((char) inputChar); } dataInputStream.close(); slaveSock.close(); parseMessage(results.toString()); results = null; } catch(Exception e) { e.printStackTrace(); Alert alertMsg = new Alert("Error", "An error has occured while reading a message from the server:\n" + e.getMessage(), null, AlertType.ERROR); alertMsg.setTimeout(Alert.FOREVER); myDisplay.setCurrent(alertMsg, resultScreen); } } }; new Thread(runnable).start(); } I am sending the message across a LAN, and I have no problems when I send short text messages instead of images. Also, I used wireshark and it seems that the desktop application is only sending part of the message. Any help would be highly appreciated. Also, everything works on the J2ME simulator. Thanks.

    Read the article

  • startActivityForResult to an activity that only displays a progressdialog

    - by Alxandr
    I'm trying to make an activity that is asked for some result. This result is normally returned instantly (in the onCreate), however, sometimes it is nesesary to wait for some internet-content to download which causes the "loader"-activity to show. What I want is that the loader-activity don't display anything more than a progressdialog (and that you can still se the old activity calling the loader-activity in the background) and I'm wondering wheather or not this is possible. The code I'm using as of now is: //ListComicsActivity.java public class ListComicsActivity extends Activity { private static final int REQUEST_COMICS = 1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_comics); Button button = (Button)findViewById(R.id.Button01); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(Intents.ACTION_GET_COMICS); startActivityForResult(intent, REQUEST_COMICS); } }); } /** Called when an activity called by using startActivityForResult finishes. */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Toast toast = Toast.makeText(this, "The activity finnished", Toast.LENGTH_SHORT); toast.show(); } } //LoaderActivity.java (answers to Intents.ACTION_GET_COMICS action-filter) public class LoaderActivity extends Activity { private Intent result = null; private ProgressDialog pg = null; private Runnable returner = new Runnable() { public void run() { if(pg != null) pg.dismiss(); LoaderActivity.this.setResult(Activity.RESULT_OK, result); LoaderActivity.this.finish(); } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String action = getIntent().getAction(); if(action.equals(Intents.ACTION_GET_COMICS)) { Runnable loader = new Runnable() { public void run() { WebProvider.DownloadComicList(); Intent intent = new Intent(); intent.setDataAndType(ComicContentProvider.COMIC_URI, "vnd.android.cursor.dir/vnd.mymir.comic"); returnResult(intent); } }; pg = ProgressDialog.show(this, "Downloading", "Please wait, retrieving data...."); Thread thread = new Thread(null, loader, "LoadComicList"); thread.start(); } else { setResult(Activity.RESULT_CANCELED); finish(); } } private void returnResult(Intent intent) { result = intent; runOnUiThread(returner); } }

    Read the article

  • How the simples GUI countdown is supposed to work?

    - by Roman
    I am trying to write the simples GUI countdown. I found in Internet some code but it is already too fancy for me. I am trying to keep it as simple as possible. So, I just want to have a window saying "You have 10 second left". The number of second should decrease every second from 10 to 0. I wrote a code. And I think I am close to the working solution. But I still missing something. Could you pleas help me to find out what is wrong? Here is my code: import javax.swing.*; public class Countdown { static JLabel label; // Method which defines the appearance of the window. private static void showGUI() { JFrame frame = new JFrame("Simple Countdown"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Some Text"); frame.add(label); frame.pack(); frame.setVisible(true); } // Define a new thread in which the countdown is counting down. static Thread counter = new Thread() { public void run() { for (int i=10; i>0; i=i-1) { updateGUI(i,label); try {Thread.sleep(1000);} catch(InterruptedException e) {}; } } }; // A method which updates GUI (sets a new value of JLabel). private static void updateGUI(final int i, final JLabel label) { SwingUtilities.invokeLater(new Runnable(i,label) { public Runnable(int i, JLabel label) { this.i = i; this.label = label; } public void run() { label.setText("You have " + i + " seconds."); } }); } // The main method (entry point). public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { showGUI(); //counter.start(); } }); //counter.start(); } } And I have several concrete question about this code: Where should I place the counter.start();? (In my code I put it on 2 places. Which one is correct?) Why compiler complains about the constructor for Runnable? It says that I have an invalid method declaration and I need to specify the returned type. ADDED: I made the suggested corrections. And then I execute the code and get: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at Worker.run(Worker.java:12) In the Worker.java in the line 12 I have: label.setText("You have " + i + " seconds.");.

    Read the article

  • ScheduledExecutorService throwable lost

    - by Andrey
    Hello, Consider I scheduled a Runnable for periodic execution with ScheduledExecutorService and there occurs some system Error like OutOfMemory. It will be silently swallowed. scheduler.scheduleWithFixedDelay(new Runnable() { @Override public void run() { throw new OutOfMemoryError(); // Swallowed } }, 0, delay, TimeUnit.SECONDS); Is it normal? Why doesn't it propagate to the container? What is the correct way to handle such errors? Thanks!

    Read the article

  • How do I read and write to a file using threads in java?

    - by WarmWaffles
    I'm writing an application where I need to read blocks in from a single file, each block is roughly 512 bytes. I am also needing to write blocks simultaneously. One of the ideas I had was BlockReader implements Runnable and BlockWriter implements Runnable and BlockManager manages both the reader and writer. The problem that I am seeing with most examples that I have found was locking problems and potential deadlock situations. Any ideas how to implement this?

    Read the article

  • SQL SERVER – SOS_SCHEDULER_YIELD – Wait Type – Day 8 of 28

    - by pinaldave
    This is a very interesting wait type and quite often seen as one of the top wait types. Let us discuss this today. From Book On-Line: Occurs when a task voluntarily yields the scheduler for other tasks to execute. During this wait the task is waiting for its quantum to be renewed. SOS_SCHEDULER_YIELD Explanation: SQL Server has multiple threads, and the basic working methodology for SQL Server is that SQL Server does not let any “runnable” thread to starve. Now let us assume SQL Server OS is very busy running threads on all the scheduler. There are always new threads coming up which are ready to run (in other words, runnable). Thread management of the SQL Server is decided by SQL Server and not the operating system. SQL Server runs on non-preemptive mode most of the time, meaning the threads are co-operative and can let other threads to run from time to time by yielding itself. When any thread yields itself for another thread, it creates this wait. If there are more threads, it clearly indicates that the CPU is under pressure. You can fun the following DMV to see how many runnable task counts there are in your system. SELECT scheduler_id, current_tasks_count, runnable_tasks_count, work_queue_count, pending_disk_io_count FROM sys.dm_os_schedulers WHERE scheduler_id < 255 GO If you notice a two-digit number in runnable_tasks_count continuously for long time (not once in a while), you will know that there is CPU pressure. The two-digit number is usually considered as a bad thing; you can read the description of the above DMV over here. Additionally, there are several other counters (%Processor Time and other processor related counters), through which you can refer to so you can validate CPU pressure along with the method explained above. Reducing SOS_SCHEDULER_YIELD wait: This is the trickiest part of this procedure. As discussed, this particular wait type relates to CPU pressure. Increasing more CPU is the solution in simple terms; however, it is not easy to implement this solution. There are other things that you can consider when this wait type is very high. Here is the query where you can find the most expensive query related to CPU from the cache Note: The query that used lots of resources but is not cached will not be caught here. SELECT SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1, ((CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(qt.TEXT) ELSE qs.statement_end_offset END - qs.statement_start_offset)/2)+1), qs.execution_count, qs.total_logical_reads, qs.last_logical_reads, qs.total_logical_writes, qs.last_logical_writes, qs.total_worker_time, qs.last_worker_time, qs.total_elapsed_time/1000000 total_elapsed_time_in_S, qs.last_elapsed_time/1000000 last_elapsed_time_in_S, qs.last_execution_time, qp.query_plan FROM sys.dm_exec_query_stats qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp ORDER BY qs.total_worker_time DESC -- CPU time You can find the most expensive queries that are utilizing lots of CPU (from the cache) and you can tune them accordingly. Moreover, you can find the longest running query and attempt to tune them if there is any processor offending code. Additionally, pay attention to total_worker_time because if that is also consistently higher, then  the CPU under too much pressure. You can also check perfmon counters of compilations as they tend to use good amount of CPU. Index rebuild is also a CPU intensive process but we should consider that main cause for this query because that is indeed needed on high transactions OLTP system utilized to reduce fragmentations. Note: The information presented here is from my experience and there is no way that I claim it to be accurate. I suggest reading Book OnLine for further clarification. All of the discussions of Wait Stats in this blog is generic and varies from system to system. It is recommended that you test this on a development server before implementing it to a production server. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, PostADay, SQL, SQL Authority, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, SQL Wait Stats, SQL Wait Types, T SQL, Technology

    Read the article

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