Search Results

Search found 215 results on 9 pages for 'threadpool'.

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

  • Spring - scheduling and pooling runnables of different state (each Runnable instance has different

    - by lisak
    Hi, I can't figure out what to use for scheduling and pooling runnables of different state (each Runnable instance has different state). I could use ScheduledExecutorFactoryBean together with MethodInvokingRunnable to supply arguments. But take a look at the key ScheduledExecutorFactoryBean method, it is designed in a way that all task should start at the beginning. protected void registerTasks(ScheduledExecutorTask[] tasks, ScheduledExecutorService executor) { for (ScheduledExecutorTask task : tasks) { Runnable runnable = getRunnableToSchedule(task); if (task.isOneTimeTask()) { executor.schedule(runnable, task.getDelay(), task.getTimeUnit()); } else { if (task.isFixedRate()) { executor.scheduleAtFixedRate(runnable, task.getDelay(), task.getPeriod(), task.getTimeUnit()); } else { executor.scheduleWithFixedDelay(runnable, task.getDelay(), task.getPeriod(), task.getTimeUnit()); } } } } I can't think of how to setup this scenario with ThreadPoolTaskScheduler. Please help me out here. Thank you EDIT: shortened version is: how to setup task scheduler that would run hundreds of "different instances of Threads (with different state) with 2 seconds interval.

    Read the article

  • How to re-use a thread in Java ?

    - by David
    I am a building a console Sudoku Solver where the main objective is raw speed. I now have a ManagerThread that starts WorkerThreads to compute the neibhbors of each cell. So one WorkerThread is started for each cell right now. How can I re-use an existing thread that has completed its work? The Thread Pool Pattern seems to be the solution, but I don't understand what to do to prevent the thread from dying once its job has been completed. ps : I do not expect to gain much performance for this particular task, just want to experiment how multi-threading works before applying it to the more complex parts of the code. Thanks

    Read the article

  • How to know if all the Thread Pool's thread are already done with its tasks?

    - by mcxiand
    I have this application that will recurse all folders in a given directory and look for PDF. If a PDF file is found, the application will count its pages using ITextSharp. I did this by using a thread to recursively scan all the folders for pdf, then if then PDF is found, this will be queued to the thread pool. The code looks like this: //spawn a thread to handle the processing of pdf on each folder. var th = new Thread(() => { pdfDirectories = Directory.GetDirectories(pdfPath); processDir(pdfDirectories); }); th.Start(); private void processDir(string[] dirs) { foreach (var dir in dirs) { pdfFiles = Directory.GetFiles(dir, "*.pdf"); processFiles(pdfFiles); string[] newdir = Directory.GetDirectories(dir); processDir(newdir); } } private void processFiles(string[] files) { foreach (var pdf in files) { ThreadPoolHelper.QueueUserWorkItem( new { path = pdf }, (data) => { processPDF(data.path); } ); } } My problem is, how do i know that the thread pool's thread has finished processing all the queued items so i can tell the user that the application is done with its intended task?

    Read the article

  • Thread pool in scala

    - by ghedas
    I have a project that is actor-based and for one part of it I must use some actors that receive message after that one actor assigns to each request separately and each actor is responsible for doing its message request, so I need something like a thread pool for actors of my project, are there any features in Scala that is useful for my necessity? how can I achieve this goal? tanks a lot for your attention!

    Read the article

  • ThreadPoolExecutor fixed thread pool with custom behaviour

    - by Simone Margaritelli
    i'm new to this topic ... i'm using a ThreadPoolExecutor created with Executors.newFixedThreadPool( 10 ) and after the pool is full i'm starting to get a RejectedExecutionException . Is there a way to "force" the executor to put the new task in a "wait" status instead of rejecting it and starting it when the pool is freed ? Thanks Issue regarding this https://github.com/evilsocket/dsploit/issues/159 Line of code involved https://github.com/evilsocket/dsploit/blob/master/src/it/evilsocket/dsploit/net/NetworkDiscovery.java#L150

    Read the article

  • Setting minimum threads in thread pool

    - by expert
    I have an application with 4 worker threads from the thread pool. It was waking up every 0.5 second. as written in msdn the thread pool monitors every 0,5 second to create idle threads. I set the nuber of minimum threads to 4 and it solved the problem - no more background activity all the time. My question is - I have another applicatiopn which has the same number of threads threads-4, but here setting min thread to 4 doesn't help but when setting min thread to 5 then the background monitoring stops. What might be the difference between 2 application with the same number of threads from the thread pool- 4 threads.On one setting min threads to 4 helps and the other only setting min threads to 5 helps?

    Read the article

  • How to increase thread-pool threads on IIS 7.0

    - by Xaqron
    Environment: Windows Server 2008 Enterprise, IIS 7.0, ASP.NET 2.0 (CLR), .NET 4.0 I have an ASP.NET application with no page and no session(HttpHandler). It a streaming server. I use two threads for processing each request so if there are 100 connected clients, then 200 threads are used. This is a dedicated server and there's no more application on the server. The problem is after 200 clients are connected (under stress testing) application refuses new clients, but if I increase the worker threads of application pool (create a web garden) then I can have 200 new happy clients per w3wp process. I feel .NET thread pool limit reaches at that point and need to increase it. Thanks

    Read the article

  • How to tell if there is an available thread in a thread pool in java

    - by Gormcito
    I am trying to proccess a queue of tasks from a database table as fast as possible while also limiting the number of threads to process the tasks. I am using a fixed sized thread pool with Executors.newFixedThreadPool(N); I want to know if there is a way of knowing if the thread pool is full, by that I mean are there currently 50 threads running, if so then I'll wait for a thread to be available before starting a new one instead of sleeping the main thread. Code of what I would like to do: ExecutorService executor = Executors.newFixedThreadPool(N); ResultSet results; while( true ) { results = getWaitingTasksStmt.executeQuery(); while( results.next() && executor.notFull() ) { executor.submit( new thread( new runnableInheritedClass(results) ) ); } }

    Read the article

  • Does WCF use the ThreadPool to bring up new instances for a PerCall service?

    - by theburningmonk
    Hi, for a PerCall WCF service whose throttling has been set to be high (say, 200 max concurrent calls) would WCF bring up a new instance and invoke the request on a threadpool thread? If it does, then does this have an impact on the total number of concurrent calls allowed? I ask because I don't seem to ever hit the max number of concurrent calls I've set in the service throttling config but instead a fraction of that number - up to 50 on a 100 MaxConcurrentCalls setting and 160 on a 200 MaxConcurrentCalls setting. Thanks,

    Read the article

  • Tools for Debugging ThreadPool Issues in Visual Studio 2010.

    - by ProfK
    I have never spent much time debugging multithreaded .NET apps (or others), and have quite a simple one to solve very quickly. Ideally I would imagined and would lurve to be able to intercept thread creation and use by worker objects, so that nothing unexpected happens while I'm on a breakpoint in my thread. Is that realistic? What else is there in VS 2010?

    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

  • Unauthorized Sharepoint WSDL from Coldfusion 8

    - by antony.trupe
    How do I solve the error: Unable to read WSDL from URL: https://workflowtest.site.edu/_vti_bin/Lists.asmx?WSDL. Error: 401 Unauthorized. I can successfully view the WSDL from the browser using the same user account. I'm not sure which authentication is being used (Basic or Integrated). How would I find that out? The code making the call is: <cfinvoke username="username" password="password" webservice="https://workflowtest.liberty.edu/_vti_bin/Lists.asmx?WSDL" method="GetList" listName="{CB02EB71-392E-4906-B512-8EC002F72436}" > The impression I get is that coldfusion doesn't like being made to authenticate to get the WSDL. Full stack trace: coldfusion.xml.rpc.XmlRpcServiceImpl$CantFindWSDLException: Unable to read WSDL from URL: https://workflowtest.liberty.edu/_vti_bin/Lists.asmx?WSDL. at coldfusion.xml.rpc.XmlRpcServiceImpl.retrieveWSDL(XmlRpcServiceImpl.java:709) at coldfusion.xml.rpc.XmlRpcServiceImpl.access$000(XmlRpcServiceImpl.java:53) at coldfusion.xml.rpc.XmlRpcServiceImpl$1.run(XmlRpcServiceImpl.java:239) at java.security.AccessController.doPrivileged(Native Method) at coldfusion.xml.rpc.XmlRpcServiceImpl.registerWebService(XmlRpcServiceImpl.java:232) at coldfusion.xml.rpc.XmlRpcServiceImpl.getWebService(XmlRpcServiceImpl.java:496) at coldfusion.xml.rpc.XmlRpcServiceImpl.getWebServiceProxy(XmlRpcServiceImpl.java:450) at coldfusion.tagext.lang.InvokeTag.doEndTag(InvokeTag.java:413) at coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:2662) at cftonytest2ecfm1787185330.runPage(/var/www/webroot/tonytest.cfm:16) at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:196) at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:370) at coldfusion.filter.CfincludeFilter.invoke(CfincludeFilter.java:65) at coldfusion.filter.ApplicationFilter.invoke(ApplicationFilter.java:279) at coldfusion.filter.RequestMonitorFilter.invoke(RequestMonitorFilter.java:48) at coldfusion.filter.MonitoringFilter.invoke(MonitoringFilter.java:40) at coldfusion.filter.PathFilter.invoke(PathFilter.java:86) at coldfusion.filter.ExceptionFilter.invoke(ExceptionFilter.java:70) at coldfusion.filter.BrowserDebugFilter.invoke(BrowserDebugFilter.java:74) at coldfusion.filter.ClientScopePersistenceFilter.invoke(ClientScopePersistenceFilter.java:28) at coldfusion.filter.BrowserFilter.invoke(BrowserFilter.java:38) at coldfusion.filter.NoCacheFilter.invoke(NoCacheFilter.java:46) at coldfusion.filter.GlobalsFilter.invoke(GlobalsFilter.java:38) at coldfusion.filter.DatasourceFilter.invoke(DatasourceFilter.java:22) at coldfusion.CfmServlet.service(CfmServlet.java:175) at coldfusion.bootstrap.BootstrapServlet.service(BootstrapServlet.java:89) at jrun.servlet.FilterChain.doFilter(FilterChain.java:86) at coldfusion.monitor.event.MonitoringServletFilter.doFilter(MonitoringServletFilter.java:42) at coldfusion.bootstrap.BootstrapFilter.doFilter(BootstrapFilter.java:46) at jrun.servlet.FilterChain.doFilter(FilterChain.java:94) at jrun.servlet.FilterChain.service(FilterChain.java:101) at jrun.servlet.ServletInvoker.invoke(ServletInvoker.java:106) at jrun.servlet.JRunInvokerChain.invokeNext(JRunInvokerChain.java:42) at jrun.servlet.JRunRequestDispatcher.invoke(JRunRequestDispatcher.java:286) at jrun.servlet.ServletEngineService.dispatch(ServletEngineService.java:543) at jrun.servlet.jrpp.JRunProxyService.invokeRunnable(JRunProxyService.java:203) at jrunx.scheduler.ThreadPool$DownstreamMetrics.invokeRunnable(ThreadPool.java:320) at jrunx.scheduler.ThreadPool$ThreadThrottle.invokeRunnable(ThreadPool.java:428) at jrunx.scheduler.ThreadPool$UpstreamMetrics.invokeRunnable(ThreadPool.java:266) at jrunx.scheduler.WorkerThread.run(WorkerThread.java:66)

    Read the article

  • Sync Vs. Async Sockets Performance in C#

    - by Michael Covelli
    Everything that I read about sockets in .NET says that the asynchronous pattern gives better performance (especially with the new SocketAsyncEventArgs which saves on the allocation). I think this makes sense if we're talking about a server with many client connections where its not possible to allocate one thread per connection. Then I can see the advantage of using the ThreadPool threads and getting async callbacks on them. But in my app, I'm the client and I just need to listen to one server sending market tick data over one tcp connection. Right now, I create a single thread, set the priority to Highest, and call Socket.Receive() with it. My thread blocks on this call and wakes up once new data arrives. If I were to switch this to an async pattern so that I get a callback when there's new data, I see two issues The threadpool threads will have default priority so it seems they will be strictly worse than my own thread which has Highest priority. I'll still have to send everything through a single thread at some point. Say that I get N callbacks at almost the same time on N different threadpool threads notifying me that there's new data. The N byte arrays that they deliver can't be processed on the threadpool threads because there's no guarantee that they represent N unique market data messages because TCP is stream based. I'll have to lock and put the bytes into an array anyway and signal some other thread that can process what's in the array. So I'm not sure what having N threadpool threads is buying me. Am I thinking about this wrong? Is there a reason to use the Async patter in my specific case of one client connected to one server?

    Read the article

  • Sync Vs. Async Sockets Performance in .NET

    - by Michael Covelli
    Everything that I read about sockets in .NET says that the asynchronous pattern gives better performance (especially with the new SocketAsyncEventArgs which saves on the allocation). I think this makes sense if we're talking about a server with many client connections where its not possible to allocate one thread per connection. Then I can see the advantage of using the ThreadPool threads and getting async callbacks on them. But in my app, I'm the client and I just need to listen to one server sending market tick data over one tcp connection. Right now, I create a single thread, set the priority to Highest, and call Socket.Receive() with it. My thread blocks on this call and wakes up once new data arrives. If I were to switch this to an async pattern so that I get a callback when there's new data, I see two issues The threadpool threads will have default priority so it seems they will be strictly worse than my own thread which has Highest priority. I'll still have to send everything through a single thread at some point. Say that I get N callbacks at almost the same time on N different threadpool threads notifying me that there's new data. The N byte arrays that they deliver can't be processed on the threadpool threads because there's no guarantee that they represent N unique market data messages because TCP is stream based. I'll have to lock and put the bytes into an array anyway and signal some other thread that can process what's in the array. So I'm not sure what having N threadpool threads is buying me. Am I thinking about this wrong? Is there a reason to use the Async patter in my specific case of one client connected to one server?

    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

  • 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

  • Parallelism in .NET – Part 15, Making Tasks Run: The TaskScheduler

    - by Reed
    In my introduction to the Task class, I specifically made mention that the Task class does not directly provide it’s own execution.  In addition, I made a strong point that the Task class itself is not directly related to threads or multithreading.  Rather, the Task class is used to implement our decomposition of tasks.  Once we’ve implemented our tasks, we need to execute them.  In the Task Parallel Library, the execution of Tasks is handled via an instance of the TaskScheduler class. The TaskScheduler class is an abstract class which provides a single function: it schedules the tasks and executes them within an appropriate context.  This class is the class which actually runs individual Task instances.  The .NET Framework provides two (internal) implementations of the TaskScheduler class. Since a Task, based on our decomposition, should be a self-contained piece of code, parallel execution makes sense when executing tasks.  The default implementation of the TaskScheduler class, and the one most often used, is based on the ThreadPool.  This can be retrieved via the TaskScheduler.Default property, and is, by default, what is used when we just start a Task instance with Task.Start(). Normally, when a Task is started by the default TaskScheduler, the task will be treated as a single work item, and run on a ThreadPool thread.  This pools tasks, and provides Task instances all of the advantages of the ThreadPool, including thread pooling for reduced resource usage, and an upper cap on the number of work items.  In addition, .NET 4 brings us a much improved thread pool, providing work stealing and reduced locking within the thread pool queues.  By using the default TaskScheduler, our Tasks are run asynchronously on the ThreadPool. There is one notable exception to my above statements when using the default TaskScheduler.  If a Task is created with the TaskCreationOptions set to TaskCreationOptions.LongRunning, the default TaskScheduler will generate a new thread for that Task, at least in the current implementation.  This is useful for Tasks which will persist for most of the lifetime of your application, since it prevents your Task from starving the ThreadPool of one of it’s work threads. The Task Parallel Library provides one other implementation of the TaskScheduler class.  In addition to providing a way to schedule tasks on the ThreadPool, the framework allows you to create a TaskScheduler which works within a specified SynchronizationContext.  This scheduler can be retrieved within a thread that provides a valid SynchronizationContext by calling the TaskScheduler.FromCurrentSynchronizationContext() method. This implementation of TaskScheduler is intended for use with user interface development.  Windows Forms and Windows Presentation Foundation both require any access to user interface controls to occur on the same thread that created the control.  For example, if you want to set the text within a Windows Forms TextBox, and you’re working on a background thread, that UI call must be marshaled back onto the UI thread.  The most common way this is handled depends on the framework being used.  In Windows Forms, Control.Invoke or Control.BeginInvoke is most often used.  In WPF, the equivelent calls are Dispatcher.Invoke or Dispatcher.BeginInvoke. As an example, say we’re working on a background thread, and we want to update a TextBlock in our user interface with a status label.  The code would typically look something like: // Within background thread work... string status = GetUpdatedStatus(); Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action( () => { statusLabel.Text = status; })); // Continue on in background method .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } This works fine, but forces your method to take a dependency on WPF or Windows Forms.  There is an alternative option, however.  Both Windows Forms and WPF, when initialized, setup a SynchronizationContext in their thread, which is available on the UI thread via the SynchronizationContext.Current property.  This context is used by classes such as BackgroundWorker to marshal calls back onto the UI thread in a framework-agnostic manner. The Task Parallel Library provides the same functionality via the TaskScheduler.FromCurrentSynchronizationContext() method.  When setting up our Tasks, as long as we’re working on the UI thread, we can construct a TaskScheduler via: TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); We then can use this scheduler on any thread to marshal data back onto the UI thread.  For example, our code above can then be rewritten as: string status = GetUpdatedStatus(); (new Task(() => { statusLabel.Text = status; })) .Start(uiScheduler); // Continue on in background method This is nice since it allows us to write code that isn’t tied to Windows Forms or WPF, but is still fully functional with those technologies.  I’ll discuss even more uses for the SynchronizationContext based TaskScheduler when I demonstrate task continuations, but even without continuations, this is a very useful construct. In addition to the two implementations provided by the Task Parallel Library, it is possible to implement your own TaskScheduler.  The ParallelExtensionsExtras project within the Samples for Parallel Programming provides nine sample TaskScheduler implementations.  These include schedulers which restrict the maximum number of concurrent tasks, run tasks on a single threaded apartment thread, use a new thread per task, and more.

    Read the article

  • TcpListener is queuing connections faster than I can clear them

    - by Matthew Brindley
    As I understand it, TcpListener will queue connections once you call Start(). Each time you call AcceptTcpClient (or BeginAcceptTcpClient), it will dequeue one item from the queue. If we load test our TcpListener app by sending 1,000 connections to it at once, the queue builds far faster than we can clear it, leading (eventually) to timeouts from the client because it didn't get a response because its connection was still in the queue. However, the server doesn't appear to be under much pressure, our app isn't consuming much CPU time and the other monitored resources on the machine aren't breaking a sweat. It feels like we're not running efficiently enough right now. We're calling BeginAcceptTcpListener and then immediately handing over to a ThreadPool thread to actually do the work, then calling BeginAcceptTcpClient again. The work involved doesn't seem to put any pressure on the machine, it's basically just a 3 second sleep followed by a dictionary lookup and then a 100 byte write to the TcpClient's stream. Here's the TcpListener code we're using: // Thread signal. private static ManualResetEvent tcpClientConnected = new ManualResetEvent(false); public void DoBeginAcceptTcpClient(TcpListener listener) { // Set the event to nonsignaled state. tcpClientConnected.Reset(); listener.BeginAcceptTcpClient( new AsyncCallback(DoAcceptTcpClientCallback), listener); // Wait for signal tcpClientConnected.WaitOne(); } public void DoAcceptTcpClientCallback(IAsyncResult ar) { // Get the listener that handles the client request, and the TcpClient TcpListener listener = (TcpListener)ar.AsyncState; TcpClient client = listener.EndAcceptTcpClient(ar); if (inProduction) ThreadPool.QueueUserWorkItem(state => HandleTcpRequest(client, serverCertificate)); // With SSL else ThreadPool.QueueUserWorkItem(state => HandleTcpRequest(client)); // Without SSL // Signal the calling thread to continue. tcpClientConnected.Set(); } public void Start() { currentHandledRequests = 0; tcpListener = new TcpListener(IPAddress.Any, 10000); try { tcpListener.Start(); while (true) DoBeginAcceptTcpClient(tcpListener); } catch (SocketException) { // The TcpListener is shutting down, exit gracefully CheckBuffer(); return; } } I'm assuming the answer will be related to using Sockets instead of TcpListener, or at least using TcpListener.AcceptSocket, but I wondered how we'd go about doing that? One idea we had was to call AcceptTcpClient and immediately Enqueue the TcpClient into one of multiple Queue<TcpClient> objects. That way, we could poll those queues on separate threads (one queue per thread), without running into monitors that might block the thread while waiting for other Dequeue operations. Each queue thread could then use ThreadPool.QueueUserWorkItem to have the work done in a ThreadPool thread and then move onto dequeuing the next TcpClient in its queue. Would you recommend this approach, or is our problem that we're using TcpListener and no amount of rapid dequeueing is going to fix that?

    Read the article

  • jboss Resteasy for java 5

    - by Anand
    Is there a resteasy version that runs on jdk 5 enviroment? I tried to compile my code in java 5 but it didnot work saying version problem. Is there a solution here? type Exception report message description The server encountered an internal error () that prevented it from fulfilling this request. exception javax.servlet.ServletException: Error instantiating servlet class org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879) org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665) org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528) org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81) org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689) java.lang.Thread.run(Thread.java:595) root cause java.lang.UnsupportedClassVersionError: Bad version number in .class file (unable to load class javax.ws.rs.core.UriInfo) org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1964) org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:933) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1405) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1284) java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) java.lang.Class.getDeclaredConstructors0(Native Method) java.lang.Class.privateGetDeclaredConstructors(Class.java:2357) java.lang.Class.getConstructor0(Class.java:2671) java.lang.Class.newInstance0(Class.java:321) java.lang.Class.newInstance(Class.java:303) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879) org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665) org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528) org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81) org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689) java.lang.Thread.run(Thread.java:595) note The full stack trace of the root cause is available in the Apache Tomcat/5.5.31 logs.

    Read the article

  • GWT RPC and GoDaddy Shared Hosting

    - by Mike Apolis
    Hi, I've deployed the sample Stock Watcher app to my GoDaddy Hosting site, and I get the error below. I've tried compiling the Project in Eclipse with JRE 1.5 because my Host is using jre 1.5. I think the issue is the "gwt-servlet.jar" is not compatible with jre 1.5. Can anyone confirm this. The project runs fine on my local machine using JRE 1.6. Unfortunately GoDaddy will not upgrade my shared hosting account jre to 1.6. GoDaddy Server Setup: Tomcat Version 5.0.27 JRE 1.5_22 Error: HTTP Status 500 - type Exception report message description The server encountered an internal error () that prevented it from fulfilling this request. exception javax.servlet.ServletException: Error allocating a servlet instance org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java: 117) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java: 535) org.apache.catalina.authenticator.SingleSignOn.invoke(SingleSignOn.java: 417) org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java: 160) org.apache.jk.server.JkCoyoteHandler.invoke(JkCoyoteHandler.java:300) org.apache.jk.common.HandlerRequest.invoke(HandlerRequest.java:374) org.apache.jk.common.ChannelSocket.invoke(ChannelSocket.java:743) org.apache.jk.common.ChannelSocket.processConnection(ChannelSocket.java: 675) org.apache.jk.common.SocketConnection.runIt(ChannelSocket.java:866) org.apache.tomcat.util.threads.ThreadPool $ControlRunnable.run(ThreadPool.java:683) java.lang.Thread.run(Thread.java:595) root cause java.lang.UnsupportedClassVersionError: Bad version number in .class file java.lang.ClassLoader.defineClass1(Native Method) java.lang.ClassLoader.defineClass(ClassLoader.java:621) java.security.SecureClassLoader.defineClass(SecureClassLoader.java: 124) org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java: 1634) org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java: 860) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java: 1307) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java: 1189) java.security.AccessController.doPrivileged(Native Method) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java: 117) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java: 535) org.apache.catalina.authenticator.SingleSignOn.invoke(SingleSignOn.java: 417) org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java: 160) org.apache.jk.server.JkCoyoteHandler.invoke(JkCoyoteHandler.java:300) org.apache.jk.common.HandlerRequest.invoke(HandlerRequest.java:374) org.apache.jk.common.ChannelSocket.invoke(ChannelSocket.java:743) org.apache.jk.common.ChannelSocket.processConnection(ChannelSocket.java: 675) org.apache.jk.common.SocketConnection.runIt(ChannelSocket.java:866) org.apache.tomcat.util.threads.ThreadPool $ControlRunnable.run(ThreadPool.java:683) java.lang.Thread.run(Thread.java:595) note The full stack trace of the root cause is available in the Apache Tomcat/5.0.27 logs. Apache Tomcat/5.0.27

    Read the article

  • C# threading pattern that will let me flush

    - by Jeff Alexander
    I have a class that implements the Begin/End Invocation pattern where I initially used ThreadPool.QueueUserWorkItem() to do thread my work. I now have the side effect where someone using my class is calling the Begin (with callback) a ton of times to do a lot of processing so ThreadPool.QueueUserWorkItem is creating a ton of threads to do the processing. That in itself isn't bad but there are instances where they want to abandon the processing and start a new process but they are forced to wait for their first request to finish. Since ThreadPool.QueueUseWorkItem() doesn't allow me to cancel the threads I am trying to come up with a better way to queue up the work and maybe use an explicit FlushQueue() method in my class to allow the caller to abandon work in my queue. Anyone have any suggestion on a threading pattern that fits my needs?

    Read the article

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