Search Results

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

Page 9/9 | < Previous Page | 5 6 7 8 9 

  • C# Monte Carlo Incremental Risk Calculation optimisation, random numbers, parallel execution

    - by m3ntat
    My current task is to optimise a Monte Carlo Simulation that calculates Capital Adequacy figures by region for a set of Obligors. It is running about 10 x too slow for where it will need to be in production and number or daily runs required. Additionally the granularity of the result figures will need to be improved down to desk possibly book level at some stage, the code I've been given is basically a prototype which is used by business units in a semi production capacity. The application is currently single threaded so I'll need to make it multi-threaded, may look at System.Threading.ThreadPool or the Microsoft Parallel Extensions library but I'm constrained to .NET 2 on the server at this bank so I may have to consider this guy's port, http://www.codeproject.com/KB/cs/aforge_parallel.aspx. I am trying my best to get them to upgrade to .NET 3.5 SP1 but it's a major exercise in an organisation of this size and might not be possible in my contract time frames. I've profiled the application using the trial of dotTrace (http://www.jetbrains.com/profiler). What other good profilers exist? Free ones? A lot of the execution time is spent generating uniform random numbers and then translating this to a normally distributed random number. They are using a C# Mersenne twister implementation. I am not sure where they got it or if it's the best way to go about this (or best implementation) to generate the uniform random numbers. Then this is translated to a normally distributed version for use in the calculation (I haven't delved into the translation code yet). Also what is the experience using the following? http://quantlib.org http://www.qlnet.org (C# port of quantlib) or http://www.boost.org Any alternatives you know of? I'm a C# developer so would prefer C#, but a wrapper to C++ shouldn't be a problem, should it? Maybe even faster leveraging the C++ implementations. I am thinking some of these libraries will have the fastest method to directly generate normally distributed random numbers, without the translation step. Also they may have some other functions that will be helpful in the subsequent calculations. Also the computer this is on is a quad core Opteron 275, 8 GB memory but Windows Server 2003 Enterprise 32 bit. Should I advise them to upgrade to a 64 bit OS? Any links to articles supporting this decision would really be appreciated. Anyway, any advice and help you may have is really appreciated.

    Read the article

  • Jetty: Stopping programatically causes "1 threads could not be stopped"

    - by Ondra Žižka
    Hi, I have an embedded Jetty 6.1.26 instance. I want to shut it down by HTTP GET sent to /shutdown. So I created a JettyShutdownServlet: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(202, "Shutting down."); resp.setContentType("text/plain"); ServletOutputStream os = resp.getOutputStream(); os.println("Shutting down."); os.close(); resp.flushBuffer(); // Stop the server. try { log.info("Shutting down the server..."); server.stop(); } catch (Exception ex) { log.error("Error when stopping Jetty server: "+ex.getMessage(), ex); } However, when I send the request, Jetty does not stop - a thread keeps hanging in org.mortbay.thread.QueuedThreadPool on the line with this.wait(): // We are idle // wait for a dispatched job synchronized (this) { if (_job==null) this.wait(getMaxIdleTimeMs()); job=_job; _job=null; } ... 2011-01-10 20:14:20,375 INFO org.mortbay.log jetty-6.1.26 2011-01-10 20:14:34,756 INFO org.mortbay.log Started [email protected]:17283 2011-01-10 20:25:40,006 INFO org.jboss.qa.mavenhoe.MavenHoeApp Shutting down the server... 2011-01-10 20:25:40,006 INFO org.mortbay.log Graceful shutdown [email protected]:17283 2011-01-10 20:25:40,006 INFO org.mortbay.log Graceful shutdown org.mortbay.jetty.servlet.Context@1672bbb{/,null} 2011-01-10 20:25:40,006 INFO org.mortbay.log Graceful shutdown org.mortbay.jetty.webapp.WebAppContext@18d30fb{/jsp,file:/home/ondra/work/Mavenhoe/trunk/target/classes/org/jboss/qa/mavenhoe/web/jsp} 2011-01-10 20:25:43,007 INFO org.mortbay.log Stopped [email protected]:17283 2011-01-10 20:25:43,009 WARN org.mortbay.log 1 threads could not be stopped 2011-01-10 20:26:43,010 INFO org.mortbay.log Shutdown hook executing 2011-01-10 20:26:43,011 INFO org.mortbay.log Shutdown hook complete It blocks for exactly one minute, then shuts down. I've added the Graceful shutdown, which should allow me to shut the server down from a servlet; However, it does not work as you can see from the log. I've solved it this way: Server server = new Server( PORT ); server.setGracefulShutdown( 3000 ); server.setStopAtShutdown(true); ... server.start(); if( server.getThreadPool() instanceof QueuedThreadPool ){ ((QueuedThreadPool) server.getThreadPool()).setMaxIdleTimeMs( 2000 ); } setMaxIdleTimeMs() needs to be called after the start(), becase the threadPool is created in start(). However, the threads are already created and waiting, so it only applies after all threads are used at least once. I don't know what else to do except some awfulness like interrupting all threads or System.exit(). Any ideas? Is there a good way? Thanks, Ondra

    Read the article

  • How to configure Jetty to reload a WebAppContext when classes are changed

    - by Guss
    I'm developing a web application and I run Jetty as the development and testing environment when I develop under Eclipse. When I make changes to Java classes, Eclipse automatically compiles them to the build directory, but Jetty won't see the changes until I stop and start the server. I know that Jetty supports "hot deployment" using ContextDeployer that will refresh updated application contexts, but it relies on a context file in a context directory being updated - which is not very useful in my case. Is there a way to set up Jetty so that it will reload the web app when any of the classes it uses is updated? My current jetty.xml looks something like this: <?xml version="1.0"?> <!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd"> <Configure id="Server" class="org.eclipse.jetty.server.Server"> <Set name="ThreadPool"><!-- bla bla --></Set> <Call name="addConnector"><!-- bla bla --></Call> <Set name="handler"> <New id="Handlers" class="org.eclipse.jetty.server.handler.HandlerCollection"> <Set name="handlers"> <Array type="org.eclipse.jetty.server.Handler"> <Item> <New id="webapp" class="org.eclipse.jetty.webapp.WebAppContext"> <Set name="displayName">My Web App</Set> <Set name="resourceBase">src/main/webapp</Set> <Set name="descriptor">src/main/webapp/WEB-INF/web.xml</Set> <Set name="contextPath">/mywebapp</Set> </New> </Item> <Item> <New id="DefaultHandler" class="org.eclipse.jetty.server.handler.DefaultHandler"/> </Item> </Array> </Set> </New> </Set> </Configure>

    Read the article

  • C# - periodic data reading and Thread.Sleep()

    - by CaldonCZE
    Hello, my C# application reads data from special USB device. The data are read as so-called "messages", each of them having 24 bytes. The amount of messages that must be read per second may differ (maximal frequency is quite high, about 700 messages per second), but the application must read them all. The only way to read the messages is by calling function "ReadMessage", that returns one message read from the device. The function is from external DLL and I cannot modify it. My solution: I've got a seperate thread, that is running all the time during the program run and it's only job is to read the messages in cycle. The received messages are then processed in main application thread. The function executed in the "reading thread" is the following: private void ReadingThreadFunction() { int cycleCount; try { while (this.keepReceivingMessages) { cycleCount++; TRxMsg receivedMessage; ReadMessage(devHandle, out receivedMessage); //...do something with the message... } } catch { //... catch exception if reading failed... } } This solution works fine and all messages are correctly received. However, the application consumes too much resources, the CPU of my computer runs at more than 80%. Therefore I'd like to reduce it. Thanks to the "cycleCount" variable I know that the "cycling speed" of the thread is about 40 000 cycles per second. This is unnecessarily too much, since I need to receive maximum 700 messagges/sec. (and the device has buffer for about 100 messages, so the cycle speed can be even a little lower) I tried to reduce the cycle speed by suspending the thread for 1 ms by Thread.Sleep(1); command. Of course, this didn't work and the cycle speed became about 70 cycles/second which was not enough to read all messages. I know that this attempt was silly, that putting the thread to sleep and then waking him up takes much longer than 1 ms. However, I don't know what else to do: Is there some other way how to slow the thread execution down (to reduce CPU consumption) other than Thread.Sleep? Or am I completely wrong and should I use something different for this task instead of Thread, maybe Threading.Timer or ThreadPool? Thanks a lot in advance for all suggestions. This is my first question here and I'm a beginner at using threads, so please excuse me if it's not clear enough.

    Read the article

  • Parallelism in .NET – Part 4, Imperative Data Parallelism: Aggregation

    - by Reed
    In the article on simple data parallelism, I described how to perform an operation on an entire collection of elements in parallel.  Often, this is not adequate, as the parallel operation is going to be performing some form of aggregation. Simple examples of this might include taking the sum of the results of processing a function on each element in the collection, or finding the minimum of the collection given some criteria.  This can be done using the techniques described in simple data parallelism, however, special care needs to be taken into account to synchronize the shared data appropriately.  The Task Parallel Library has tools to assist in this synchronization. The main issue with aggregation when parallelizing a routine is that you need to handle synchronization of data.  Since multiple threads will need to write to a shared portion of data.  Suppose, for example, that we wanted to parallelize a simple loop that looked for the minimum value within a dataset: double min = double.MaxValue; foreach(var item in collection) { double value = item.PerformComputation(); min = System.Math.Min(min, value); } .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 seems like a good candidate for parallelization, but there is a problem here.  If we just wrap this into a call to Parallel.ForEach, we’ll introduce a critical race condition, and get the wrong answer.  Let’s look at what happens here: // Buggy code! Do not use! double min = double.MaxValue; Parallel.ForEach(collection, item => { double value = item.PerformComputation(); min = System.Math.Min(min, value); }); This code has a fatal flaw: min will be checked, then set, by multiple threads simultaneously.  Two threads may perform the check at the same time, and set the wrong value for min.  Say we get a value of 1 in thread 1, and a value of 2 in thread 2, and these two elements are the first two to run.  If both hit the min check line at the same time, both will determine that min should change, to 1 and 2 respectively.  If element 1 happens to set the variable first, then element 2 sets the min variable, we’ll detect a min value of 2 instead of 1.  This can lead to wrong answers. Unfortunately, fixing this, with the Parallel.ForEach call we’re using, would require adding locking.  We would need to rewrite this like: // Safe, but slow double min = double.MaxValue; // Make a "lock" object object syncObject = new object(); Parallel.ForEach(collection, item => { double value = item.PerformComputation(); lock(syncObject) min = System.Math.Min(min, value); }); This will potentially add a huge amount of overhead to our calculation.  Since we can potentially block while waiting on the lock for every single iteration, we will most likely slow this down to where it is actually quite a bit slower than our serial implementation.  The problem is the lock statement – any time you use lock(object), you’re almost assuring reduced performance in a parallel situation.  This leads to two observations I’ll make: When parallelizing a routine, try to avoid locks. That being said: Always add any and all required synchronization to avoid race conditions. These two observations tend to be opposing forces – we often need to synchronize our algorithms, but we also want to avoid the synchronization when possible.  Looking at our routine, there is no way to directly avoid this lock, since each element is potentially being run on a separate thread, and this lock is necessary in order for our routine to function correctly every time. However, this isn’t the only way to design this routine to implement this algorithm.  Realize that, although our collection may have thousands or even millions of elements, we have a limited number of Processing Elements (PE).  Processing Element is the standard term for a hardware element which can process and execute instructions.  This typically is a core in your processor, but many modern systems have multiple hardware execution threads per core.  The Task Parallel Library will not execute the work for each item in the collection as a separate work item. Instead, when Parallel.ForEach executes, it will partition the collection into larger “chunks” which get processed on different threads via the ThreadPool.  This helps reduce the threading overhead, and help the overall speed.  In general, the Parallel class will only use one thread per PE in the system. Given the fact that there are typically fewer threads than work items, we can rethink our algorithm design.  We can parallelize our algorithm more effectively by approaching it differently.  Because the basic aggregation we are doing here (Min) is communitive, we do not need to perform this in a given order.  We knew this to be true already – otherwise, we wouldn’t have been able to parallelize this routine in the first place.  With this in mind, we can treat each thread’s work independently, allowing each thread to serially process many elements with no locking, then, after all the threads are complete, “merge” together the results. This can be accomplished via a different set of overloads in the Parallel class: Parallel.ForEach<TSource,TLocal>.  The idea behind these overloads is to allow each thread to begin by initializing some local state (TLocal).  The thread will then process an entire set of items in the source collection, providing that state to the delegate which processes an individual item.  Finally, at the end, a separate delegate is run which allows you to handle merging that local state into your final results. To rewriting our routine using Parallel.ForEach<TSource,TLocal>, we need to provide three delegates instead of one.  The most basic version of this function is declared as: public static ParallelLoopResult ForEach<TSource, TLocal>( IEnumerable<TSource> source, Func<TLocal> localInit, Func<TSource, ParallelLoopState, TLocal, TLocal> body, Action<TLocal> localFinally ) The first delegate (the localInit argument) is defined as Func<TLocal>.  This delegate initializes our local state.  It should return some object we can use to track the results of a single thread’s operations. The second delegate (the body argument) is where our main processing occurs, although now, instead of being an Action<T>, we actually provide a Func<TSource, ParallelLoopState, TLocal, TLocal> delegate.  This delegate will receive three arguments: our original element from the collection (TSource), a ParallelLoopState which we can use for early termination, and the instance of our local state we created (TLocal).  It should do whatever processing you wish to occur per element, then return the value of the local state after processing is completed. The third delegate (the localFinally argument) is defined as Action<TLocal>.  This delegate is passed our local state after it’s been processed by all of the elements this thread will handle.  This is where you can merge your final results together.  This may require synchronization, but now, instead of synchronizing once per element (potentially millions of times), you’ll only have to synchronize once per thread, which is an ideal situation. Now that I’ve explained how this works, lets look at the code: // Safe, and fast! double min = double.MaxValue; // Make a "lock" object object syncObject = new object(); Parallel.ForEach( collection, // First, we provide a local state initialization delegate. () => double.MaxValue, // Next, we supply the body, which takes the original item, loop state, // and local state, and returns a new local state (item, loopState, localState) => { double value = item.PerformComputation(); return System.Math.Min(localState, value); }, // Finally, we provide an Action<TLocal>, to "merge" results together localState => { // This requires locking, but it's only once per used thread lock(syncObj) min = System.Math.Min(min, localState); } ); Although this is a bit more complicated than the previous version, it is now both thread-safe, and has minimal locking.  This same approach can be used by Parallel.For, although now, it’s Parallel.For<TLocal>.  When working with Parallel.For<TLocal>, you use the same triplet of delegates, with the same purpose and results. Also, many times, you can completely avoid locking by using a method of the Interlocked class to perform the final aggregation in an atomic operation.  The MSDN example demonstrating this same technique using Parallel.For uses the Interlocked class instead of a lock, since they are doing a sum operation on a long variable, which is possible via Interlocked.Add. By taking advantage of local state, we can use the Parallel class methods to parallelize algorithms such as aggregation, which, at first, may seem like poor candidates for parallelization.  Doing so requires careful consideration, and often requires a slight redesign of the algorithm, but the performance gains can be significant if handled in a way to avoid excessive synchronization.

    Read the article

  • Problems with shutting down JBoss in Eclipse if I change JNDI port

    - by Balint Pato
    1st phase I have a problem shutting down my running JBoss instance under Eclipse since I changed the JNDI port of JBoss. Of course I can shut it down from the console view but not with the stop button (it still searches JNDI port at the default 1099 port). I'm looking forward to any solutions. Thank you! Used environment: JBoss 4.0.2 (using default) Eclipse 3.4.0. (using JBoss Tools 2.1.1.GA) Default ports: 1098, 1099 Changed ports: 11098, 11099 I changed the following part in jbosspath/server/default/conf/jboss-service.xml: <!-- ==================================================================== --> <!-- JNDI --> <!-- ==================================================================== --> <mbean code="org.jboss.naming.NamingService" name="jboss:service=Naming" xmbean-dd="resource:xmdesc/NamingService-xmbean.xml"> <!-- The call by value mode. true if all lookups are unmarshalled using the caller's TCL, false if in VM lookups return the value by reference. --> <attribute name="CallByValue">false</attribute> <!-- The listening port for the bootstrap JNP service. Set this to -1 to run the NamingService without the JNP invoker listening port. --> <attribute name="Port">11099</attribute> <!-- The bootstrap JNP server bind address. This also sets the default RMI service bind address. Empty == all addresses --> <attribute name="BindAddress">${jboss.bind.address}</attribute> <!-- The port of the RMI naming service, 0 == anonymous --> <attribute name="RmiPort">11098</attribute> <!-- The RMI service bind address. Empty == all addresses --> <attribute name="RmiBindAddress">${jboss.bind.address}</attribute> <!-- The thread pool service used to control the bootstrap lookups --> <depends optional-attribute-name="LookupPool" proxy-type="attribute">jboss.system:service=ThreadPool</depends> </mbean> <mbean code="org.jboss.naming.JNDIView" name="jboss:service=JNDIView" xmbean-dd="resource:xmdesc/JNDIView-xmbean.xml"> </mbean> Eclipse setup: About my JBoss Tools preferences: I had a previous version, I got this problem, I read about some bugfix in JbossTools, so updated to 2.1.1.GA. Now the buttons changed, and I've got a new preferences view, but I cannot modify anything...seems to be abnormal as well: Error dialog: The stacktrace: javax.naming.CommunicationException: Could not obtain connection to any of these urls: localhost:1099 [Root exception is javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]]] at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1385) at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:579) at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:572) at javax.naming.InitialContext.lookup(InitialContext.java:347) at org.jboss.Shutdown.main(Shutdown.java:202) Caused by: javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]] at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:254) at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1370) ... 4 more Caused by: javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect] at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:228) ... 5 more Caused by: java.net.ConnectException: Connection refused: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158) at java.net.Socket.connect(Socket.java:452) at java.net.Socket.connect(Socket.java:402) at java.net.Socket.<init>(Socket.java:309) at java.net.Socket.<init>(Socket.java:211) at org.jnp.interfaces.TimedSocketFactory.createSocket(TimedSocketFactory.java:69) at org.jnp.interfaces.TimedSocketFactory.createSocket(TimedSocketFactory.java:62) at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:224) ... 5 more Exception in thread "main" 2nd phase: After creating a new Server in File/new/other/server, it did appear in the preferences tab. Now the stop button is working (the server receives the shutdown messages without any additional modification of the jndi port -- there is no opportunity for it now) but it still throws an error message, though different, it's without exception stack trace: "Server JBoss 4.0 Server failed to stop."

    Read the article

  • Defines JEE 5 the handling of commit error using bean managed transactions?

    - by marabol
    I'm using glassfish 2.1 and 2.1.1. If I've a bean method annotated by @TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW). After doing some JPA stuff the commit fails in the afterCompletion-Phase of JTS. GlassFish logs this failure only. And the caller of this bean method has no chance to know something goes wrong. So I wonder, if there is any definition how a jee 5 server has to handle exceptions while commiting. I would expect any runtime exception. I'm using stateless beans. With SessionSynchronisation I could get the commit failue, if I use statefull beans. Is it possible to intercept, so I can throw an exception, that I've declared in my interface? This is the whole exception stacktrace: [#|2010-05-06T12:15:54.840+0000|WARNING|sun-appserver2.1|oracle.toplink.essentials.session.file:/C:/glassfish/domains/domain1/applications/j2ee-apps/my-ear-1.0.0-SNAPSHOT/my-jar-1.1.8_jar/-myPu.transaction|_ThreadID=25;_ThreadName=p: thread-pool-1; w: 15;_RequestID=67a475a1-25c3-4416-abea-0d159f715373;| java.lang.RuntimeException: Got exception during XAResource.end: oracle.jdbc.xa.OracleXAException at com.sun.enterprise.distributedtx.J2EETransactionManagerOpt.delistResource(J2EETransactionManagerOpt.java:224) at com.sun.enterprise.resource.ResourceManagerImpl.unregisterResource(ResourceManagerImpl.java:265) at com.sun.enterprise.resource.ResourceManagerImpl.delistResource(ResourceManagerImpl.java:223) at com.sun.enterprise.resource.PoolManagerImpl.resourceClosed(PoolManagerImpl.java:400) at com.sun.enterprise.resource.ConnectorAllocator$ConnectionListenerImpl.connectionClosed(ConnectorAllocator.java:72) at com.sun.gjc.spi.ManagedConnection.connectionClosed(ManagedConnection.java:639) at com.sun.gjc.spi.base.ConnectionHolder.close(ConnectionHolder.java:201) at com.sun.gjc.spi.jdbc40.ConnectionHolder40.close(ConnectionHolder40.java:519) at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.closeDatasourceConnection(DatabaseAccessor.java:394) at oracle.toplink.essentials.internal.databaseaccess.DatasourceAccessor.closeConnection(DatasourceAccessor.java:382) at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.closeConnection(DatabaseAccessor.java:417) at oracle.toplink.essentials.internal.databaseaccess.DatasourceAccessor.afterJTSTransaction(DatasourceAccessor.java:115) at oracle.toplink.essentials.threetier.ClientSession.afterTransaction(ClientSession.java:119) at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.afterTransaction(UnitOfWorkImpl.java:1841) at oracle.toplink.essentials.transaction.AbstractSynchronizationListener.afterCompletion(AbstractSynchronizationListener.java:170) at oracle.toplink.essentials.transaction.JTASynchronizationListener.afterCompletion(JTASynchronizationListener.java:102) at com.sun.jts.jta.SynchronizationImpl.after_completion(SynchronizationImpl.java:154) at com.sun.jts.CosTransactions.RegisteredSyncs.distributeAfter(RegisteredSyncs.java:210) at com.sun.jts.CosTransactions.TopCoordinator.afterCompletion(TopCoordinator.java:2585) at com.sun.jts.CosTransactions.CoordinatorTerm.commit(CoordinatorTerm.java:433) at com.sun.jts.CosTransactions.TerminatorImpl.commit(TerminatorImpl.java:250) at com.sun.jts.CosTransactions.CurrentImpl.commit(CurrentImpl.java:623) at com.sun.jts.jta.TransactionManagerImpl.commit(TransactionManagerImpl.java:309) at com.sun.enterprise.distributedtx.J2EETransactionManagerImpl.commit(J2EETransactionManagerImpl.java:1029) at com.sun.enterprise.distributedtx.J2EETransactionManagerOpt.commit(J2EETransactionManagerOpt.java:398) at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:3817) at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:3610) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1379) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1316) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:205) at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:127) at $Proxy127.myNewTxMethod(Unknown Source) at mypackage.MyBean2.myMethod(MyBean2.java:197) at mypackage.MyBean2.myMethod2(MyBean2.java:166) at mypackage.MyBean2.myMethod3(MyBean2.java:105) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.sun.enterprise.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1011) at com.sun.enterprise.security.SecurityUtil.invoke(SecurityUtil.java:175) at com.sun.ejb.containers.BaseContainer.invokeTargetBeanMethod(BaseContainer.java:2920) at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4011) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:197) at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:127) at $Proxy158.myMethod3(Unknown Source) at mypackage.MyBean3.myMethod4(MyBean3.java:94) at mypackage.MyBean3.onMessage(MyBean3.java:85) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.sun.enterprise.security.SecurityUtil$2.run(SecurityUtil.java:181) at java.security.AccessController.doPrivileged(Native Method) at com.sun.enterprise.security.application.EJBSecurityManager.doAsPrivileged(EJBSecurityManager.java:985) at com.sun.enterprise.security.SecurityUtil.invoke(SecurityUtil.java:186) at com.sun.ejb.containers.BaseContainer.invokeTargetBeanMethod(BaseContainer.java:2920) at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4011) at com.sun.ejb.containers.MessageBeanContainer.deliverMessage(MessageBeanContainer.java:1111) at com.sun.ejb.containers.MessageBeanListenerImpl.deliverMessage(MessageBeanListenerImpl.java:74) at com.sun.enterprise.connectors.inflow.MessageEndpointInvocationHandler.invoke(MessageEndpointInvocationHandler.java:179) at $Proxy192.onMessage(Unknown Source) at com.sun.messaging.jms.ra.OnMessageRunner.run(OnMessageRunner.java:258) at com.sun.enterprise.connectors.work.OneWork.doWork(OneWork.java:76) at com.sun.corba.ee.impl.orbutil.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:555) |#]

    Read the article

  • Help with Silverlight Sockets and Message delivery

    - by pixel3cs
    There are 4 months since I stopped developing my Silverlight Multiplayer Chess game. The problem was a bug wich I couldn't reproduce. Sice I got some free time this week I managed to discover the problem and I am now able to reproduce the bug. It seems that if I send 10 messages from client, one after another, with no delay between them, just like in the below example // when I press Enter, the client will 10 messages with no delay between them private void textBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter && textBox.Text.Length > 0) { for (int i = 0; i < 10; i++) { MessageBuilder mb = new MessageBuilder(); mb.Writer.Write((byte)GameCommands.NewChatMessageInTable); mb.Writer.Write(string.Format("{0}{2}: {1}", ClientVars.PlayerNickname, textBox.Text, i)); SendChatMessageEvent(mb.GetMessage()); //System.Threading.Thread.Sleep(100); } textBox.Text = string.Empty; } } // the method used by client to send a message to server public void SendData(Message message) { if (socket.Connected) { SocketAsyncEventArgs myMsg = new SocketAsyncEventArgs(); myMsg.RemoteEndPoint = socket.RemoteEndPoint; byte[] buffer = message.Buffer; myMsg.SetBuffer(buffer, 0, buffer.Length); socket.SendAsync(myMsg); } else { string err = "Server does not respond. You are disconnected."; socket.Close(); uiContext.Post(this.uiClient.ProcessOnErrorData, err); } } // the method used by server to receive data from client private void OnDataReceived(IAsyncResult async) { ClientSocketPacket client = async.AsyncState as ClientSocketPacket; int count = 0; try { if (client.Socket.Connected) count = client.Socket.EndReceive(async); // THE PROBLEM IS HERE // IF SERVER WAS RECEIVE ALL MESSAGES SEPARATELY, ONE BY ONE, THE COUNT // WAS ALWAYS 15, BUT BECAUSE THE SERVER RECEIVE 3 MESSAGES IN 1, THE COUNT // IS SOMETIME 45 } catch { HandleException(client); } client.MessageStream.Write(client.Buffer, 0, count); Message message; while (client.MessageStream.Read(out message)) { message.Tag = client; ThreadPool.QueueUserWorkItem(new WaitCallback(this.processingThreadEvent.ServerGotData), message); totalReceivedBytes += message.Buffer.Length; } try { if (client.Socket.Connected) client.Socket.BeginReceive(client.Buffer, 0, client.Buffer.Length, 0, new AsyncCallback(OnDataReceived), client); } catch { HandleException(client); } } there are sent only 3 big messages, and every big message contain 3 or 4 small messages. This is not the behavior I want. If I put a 100 milliseconds delay between message delivery, everything is work fine, but in a real world scenario users can send messages to server even at 1 millisecond between them. Are there any settings to be done in order to make the client send only one message at a time, or Even if I receive 3 messages in 1, are they full messages all the time (I dont't want to receive 2.5 messages in one big message) ? because if they are, I can read them and treat this new situation

    Read the article

  • Typesafe fire-and-forget asynchronous delegate invocation in C#

    - by LBushkin
    I recently found myself needing a typesafe "fire-and-forget" mechanism for running code asynchronously. Ideally, what I would want to do is something like: var myAction = (Action)(() => Console.WriteLine("yada yada")); myAction.FireAndForget(); // async invocation Unfortunately, the obvious choice of calling BeginInvoke() without a corresponding EndInvoke() does not work - it results in a slow resource leak (since the asyn state is held by the runtime and never released ... it's expecting an eventual call to EndInvoke(). I also can't run the code on the .NET thread pool because it may take a very long time to complete (it's advised to only run relatively short-lived code on the thread pool) - this makes it impossible to use the ThreadPool.QueueUserWorkItem(). Initially, I only needed this behavior for methods whose signature matches Action, Action<...>, or Func<...>. So I put together a set of extension methods (see listing below) that let me do this without running into the resource leak. There are overloads for each version of Action/Func. Unfortunately, I now want to port this code to .NET 4 where the number of generic parameters on Action and Func have been increased substantially. Before I write a T4 script to generate these, I was also hoping to find a simpler more elegant way to do this. Any ideas are welcome. public static class AsyncExt { public static void FireAndForget( this Action action ) { action.BeginInvoke(OnActionCompleted, action); } public static void FireAndForget<T1>( this Action<T1> action, T1 arg1 ) { action.BeginInvoke(arg1, OnActionCompleted<T1>, action); } public static void FireAndForget<T1,T2>( this Action<T1,T2> action, T1 arg1, T2 arg2 ) { action.BeginInvoke(arg1, arg2, OnActionCompleted<T1, T2>, action); } public static void FireAndForget<TResult>(this Func<TResult> func, TResult arg1) { func.BeginInvoke(OnFuncCompleted<TResult>, func); } public static void FireAndForget<T1,TResult>(this Func<T1, TResult> action, T1 arg1) { action.BeginInvoke(arg1, OnFuncCompleted<T1,TResult>, action); } // more overloads of FireAndForget<..>() for Action<..> and Func<..> private static void OnActionCompleted( IAsyncResult result ) { var action = (Action)result.AsyncState; action.EndInvoke(result); } private static void OnActionCompleted<T1>( IAsyncResult result ) { var action = (Action<T1>)result.AsyncState; action.EndInvoke( result ); } private static void OnActionCompleted<T1,T2>(IAsyncResult result) { var action = (Action<T1,T2>)result.AsyncState; action.EndInvoke(result); } private static void OnFuncCompleted<TResult>( IAsyncResult result ) { var func = (Func<TResult>)result.AsyncState; func.EndInvoke( result ); } private static void OnFuncCompleted<T1,TResult>(IAsyncResult result) { var func = (Func<T1, TResult>)result.AsyncState; func.EndInvoke(result); } // more overloads of OnActionCompleted<> and OnFuncCompleted<> }

    Read the article

  • "Could not establish secure channel for SSL/TLS" in .NET CF application on smart phone

    - by Stefan Mohr
    I have a stubborn communications issue with an application running on the .NET Compact Framework 3.5 on Windows Mobile smartphones. I am constructing a web request using this code: UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] Data = encoding.GetBytes(HttpUtility.ConstructQueryString(parameters)); httpRequest = WebRequest.Create((domain)) as HttpWebRequest; httpRequest.Timeout = 10000000; httpRequest.ReadWriteTimeout = 10000000; httpRequest.Credentials = CredentialCache.DefaultCredentials; httpRequest.Method = "POST"; httpRequest.ContentType = "application/x-www-form-urlencoded"; httpRequest.ContentLength = Data.Length; Stream SendReq = httpRequest.GetRequestStream(); SendReq.Write(Data, 0, Data.Length); SendReq.Close(); HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse(); return httpResponse.GetResponseStream(); The web service functions by receiving a JSON-encoded document as part of the URL (eg. https://site.com/ws/sync??document={"version":"1.0.0","items":[{"item_1":"item1"}]}&user=usr&password=pw), and as a response receives another JSON document as response data. This code runs fine on all emulators and PDAs running WM 5 and 6. We have seen an issue with a couple of customers running Treo smartphones (and only on the Sprint network). We have tested the code on an identical device on the AT&T network (via DeviceAnywhere) and once again the code worked as we expected. This has to be some sort of security policy on the phone, but we've been unable to determine a workaround or diagnose it thoroughly as we cannot reproduce it in house and have had to resort to getting users to assist with running test drivers for us. When this code executes, the user's device throws the following exception: System.Net.WebException Could not establish secure channel for SSL/TLS Stack trace: at System.Net.HttpWebRequest.finishGetRequestStream() at System.Net.HttpWebRequest.GetRequestStream() at OurApp.GetResponseStream(String domain, Hashtable parameters) inner exception: System.IO.IOException Authentication failed because the remote party has closed the transport stream. Stack trace: at System.Net.SslConnectionState.ClientSideHandshake() at System.Net.SslConnectionState.PerformClientHandShake() at System.Net.Connection.connect(Object ignored) at System.Threading.ThreadPool.WorkItem.doWork(Object o) at System.Threading.Timer.ring() Examining the server Apache logs shows no hits from the user's IP - I don't think the device is even attempting to send a packet before failing. If relevant, the server is running Apache on Linux and is written using the TurboGears Python framework. The server certificate is issued by a CA and is still valid. The test driver where this error was copied from was not code signed, however the same error (without the error messages) is signed with a GeoTrust certificate so we don't believe this is a code signing issue. The application installs and launches without issue on all phones - it's just establishing this SSL connection that is breaking for these users. One significant issue in troubleshooting is that there is a substantial inconvenience each time we try out a solution (need to find a "volunteer" customer), so we're really looking for a silver bullet or a better understanding of the handshaking process so we can be reasonably confident we only need to ask the user to test it one or two more times. One final mention: we have tried the sync both over ActiveSync and also over GPRS with identical results. Any thoughts would be greatly appreciated!

    Read the article

  • The Incremental Architect&acute;s Napkin - #2 - Balancing the forces

    - by Ralf Westphal
    Originally posted on: http://geekswithblogs.net/theArchitectsNapkin/archive/2014/06/02/the-incremental-architectacutes-napkin---2---balancing-the-forces.aspxCategorizing requirements is the prerequisite for ecconomic architectural decisions. Not all requirements are created equal. However, to truely understand and describe the requirement forces pulling on software development, I think further examination of the requirements aspects is varranted. Aspects of Functionality There are two sides to Functionality requirements. It´s about what a software should do. I call that the Operations it implements. Operations are defined by expressions and control structures or calls to frameworks of some sort, i.e. (business) logic statements. Operations calculate, transform, aggregate, validate, send, receive, load, store etc. Operations are about behavior; they take input and produce output by considering state. I´m not using the term “function” here, because functions - or methods or sub-programs - are not necessary to implement Operations. Functions belong to a different sub-aspect of requirements (see below). Operations alone are not enough, though, to make a customer happy with regard to his/her Functionality requirements. Only correctly implemented Operations provide full value. This should make clear, why testing is so important. And not just manual tests during development of some operational feature, but automated tests. Because only automated tests scale when over time the number of operations increases. Without automated tests there is no guarantee formerly correct operations are still correct after more got added. To retest all previous operations manually is infeasible. So whoever relies just on manual tests is not really balancing the two forces Operations and Correctness. With manual tests more weight is put on the side of the scale of Operations. That might be ok for a short period of time - but in the long run it will bite you. You need to plan for Correctness in the long run from the first day of your project on. Aspects of Quality As important as Functionality is, it´s not the driver for software development. No software has ever been written to just implement some operation in code. We don´t need computers just to do something. All computers can do with software we can do without them. Well, at least given enough time and resources. We could calculate the most complex formulas without computers. We could do auctions with millions of people without computers. The only reason we want computers to help us with this and a million other Operations is… We don´t want to wait for the results very long. Or we want less errors. Or we want easier accessability to complicated solutions. So the main reason for customers to buy/order software is some Quality. They want some Functionality with a higher Quality (e.g. performance, scalability, usability, security…) than without the software. But Qualities come in at least two flavors: Most important are Primary Qualities. That´s the Qualities software truely is written for. Take an online auction website for example. Its Primary Qualities are performance, scalability, and usability, I´d say. Auctions should come within reach of millions of people; setting up an auction should be very easy; finding a suitable auction and bidding on it should be as fast as possible. Only if those Qualities have been implemented does security become relevant. A secure auction website is important - but not as important as a fast auction website. Nobody would want to use the most secure auction website if it was unbearably slow. But there would be people willing to use the fastest auction website even it was lacking security. That´s why security - with regard to online auction software - is not a Primary Quality, but just a Secondary Quality. It´s a supporting quality, so to speak. It does not deliver value by itself. With a password manager software this might be different. There security might be a Primary Quality. Please get me right: I don´t want to denigrate any Quality. There´s a long list of non-functional requirements at Wikipedia. They are all created equal - but that does not mean they are equally important for all software projects. When confronted with Quality requirements check with the customer which are primary and which are secondary. That will help to make good economical decisions when in a crunch. Resources are always limited - but requirements are a bottomless ocean. Aspects of Security of Investment Functionality and Quality are traditionally the requirement aspects cared for most - by customers and developers alike. Even today, when pressure rises in a project, tunnel vision will focus on them. Any measures to create and hold up Security of Investment (SoI) will be out of the window pretty quickly. Resistance to customers and/or management is futile. As long as SoI is not placed on equal footing with Functionality and Quality it´s bound to suffer under pressure. To look closer at what SoI means will help to become more conscious about it and make customers and management aware of the risks of neglecting it. SoI to me has two facets: Production Efficiency (PE) is about speed of delivering value. Customers like short response times. Short response times mean less money spent. So whatever makes software development faster supports this requirement. This must not lead to duct tape programming and banging out features by the dozen, though. Because customers don´t just want Operations and Quality, but also Correctness. So if Correctness gets compromised by focussing too much on Production Efficiency it will fire back. Customers want PE not just today, but over the whole course of a software´s lifecycle. That means, it´s not just about coding speed, but equally about code quality. If code quality leads to rework the PE is on an unsatisfactory level. Also if code production leads to waste it´s unsatisfactory. Because the effort which went into waste could have been used to produce value. Rework and waste cost money. Rework and waste abound, however, as long as PE is not addressed explicitly with management and customers. Thanks to the Agile and Lean movements that´s increasingly the case. Nevertheless more could and should be done in many teams. Each and every developer should keep in mind that Production Efficiency is as important to the customer as Functionality and Quality - whether he/she states it or not. Making software development more efficient is important - but still sooner or later even agile projects are going to hit a glas ceiling. At least as long as they neglect the second SoI facet: Evolvability. Delivering correct high quality functionality in short cycles today is good. But not just any software structure will allow this to happen for an indefinite amount of time.[1] The less explicitly software was designed the sooner it´s going to get stuck. Big ball of mud, monolith, brownfield, legacy code, technical debt… there are many names for software structures that have lost the ability to evolve, to be easily changed to accomodate new requirements. An evolvable code base is the opposite of a brownfield. It´s code which can be easily understood (by developers with sufficient domain expertise) and then easily changed to accomodate new requirements. Ideally the costs of adding feature X to an evolvable code base is independent of when it is requested - or at least the costs should only increase linearly, not exponentially.[2] Clean Code, Agile Architecture, and even traditional Software Engineering are concerned with Evolvability. However, it seems no systematic way of achieving it has been layed out yet. TDD + SOLID help - but still… When I look at the design ability reality in teams I see much room for improvement. As stated previously, SoI - or to be more precise: Evolvability - can hardly be measured. Plus the customer rarely states an explicit expectation with regard to it. That´s why I think, special care must be taken to not neglect it. Postponing it to some large refactorings should not be an option. Rather Evolvability needs to be a core concern for every single developer day. This should not mean Evolvability is more important than any of the other requirement aspects. But neither is it less important. That´s why more effort needs to be invested into it, to bring it on par with the other aspects, which usually are much more in focus. In closing As you see, requirements are of quite different kinds. To not take that into account will make it harder to understand the customer, and to make economic decisions. Those sub-aspects of requirements are forces pulling in different directions. To improve performance might have an impact on Evolvability. To increase Production Efficiency might have an impact on security etc. No requirement aspect should go unchecked when deciding how to allocate resources. Balancing should be explicit. And it should be possible to trace back each decision to a requirement. Why is there a null-check on parameters at the start of the method? Why are there 5000 LOC in this method? Why are there interfaces on those classes? Why is this functionality running on the threadpool? Why is this function defined on that class? Why is this class depending on three other classes? These and a thousand more questions are not to mean anything should be different in a code base. But it´s important to know the reason behind all of these decisions. Because not knowing the reason possibly means waste and having decided suboptimally. And how do we ensure to balance all requirement aspects? That needs practices and transparency. Practices means doing things a certain way and not another, even though that might be possible. We´re dealing with dangerous tools here. Like a knife is a dangerous tool. Harm can be done if we use our tools in just any way at the whim of the moment. Over the centuries rules and practices have been established how to use knifes. You don´t put them in peoples´ legs just because you´re feeling like it. You hand over a knife with the handle towards the receiver. You might not even be allowed to cut round food like potatos or eggs with it. The same should be the case for dangerous tools like object-orientation, remote communication, threads etc. We need practices to use them in a way so requirements are balanced almost automatically. In addition, to be able to work on software as a team we need transparency. We need means to share our thoughts, to work jointly on mental models. So far our tools are focused on working with code. Testing frameworks, build servers, DI containers, intellisense, refactoring support… That´s all nice and well. I don´t want to miss any of that. But I think it´s not enough. We´re missing mental tools, tools for making thinking and talking about software (independently of code) easier. You might think, enough of such tools already exist like all those UML diagram types or Flow Charts. But then, isn´t it strange, hardly any team is using them to design software? Or is that just due to a lack of education? I don´t think so. It´s a matter value/weight ratio: the current mental tools are too heavy weight compared to the value they deliver. So my conclusion is, we need lightweight tools to really be able to balance requirements. Software development is complex. We need guidance not to forget important aspects. That´s like with flying an airplane. Pilots don´t just jump in and take off for their destination. Yes, there are times when they are “flying by the seats of their pants”, when they are just experts doing thing intuitively. But most of the time they are going through honed practices called checklist. See “The Checklist Manifesto” for very enlightening details on this. Maybe then I should say it like this: We need more checklists for the complex businss of software development.[3] But that´s what software development mostly is about: changing software over an unknown period of time. It needs to be corrected in order to finally provide promised operations. It needs to be enhanced to provide ever more operations and qualities. All this without knowing when it´s going to stop. Probably never - until “maintainability” hits a wall when the technical debt is too large, the brownfield too deep. Software development is not a sprint, is not a marathon, not even an ultra marathon. Because to all this there is a foreseeable end. Software development is like continuously and foreever running… ? And sometimes I dare to think that costs could even decrease over time. Think of it: With each feature a software becomes richer in functionality. So with each additional feature the chance of there being already functionality helping its implementation increases. That should lead to less costs of feature X if it´s requested later than sooner. X requested later could stand on the shoulders of previous features. Alas, reality seems to be far from this despite 20+ years of admonishing developers to think in terms of reusability.[1] ? Please don´t get me wrong: I don´t want to bog down the “art” of software development with heavyweight practices and heaps of rules to follow. The framework we need should be lightweight. It should not stand in the way of delivering value to the customer. It´s purpose is even to make that easier by helping us to focus and decreasing waste and rework. ?

    Read the article

  • Asynchronous Streaming in ASP.NET WebApi

    - by andresv
     Hi everyone, if you use the cool MVC4 WebApi you might encounter yourself in a common situation where you need to return a rather large amount of data (most probably from a database) and you want to accomplish two things: Use streaming so the client fetch the data as needed, and that directly correlates to more fetching in the server side (from our database, for example) without consuming large amounts of memory. Leverage the new MVC4 WebApi and .NET 4.5 async/await asynchronous execution model to free ASP.NET Threadpool threads (if possible).  So, #1 and #2 are not directly related to each other and we could implement our code fulfilling one or the other, or both. The main point about #1 is that we want our method to immediately return to the caller a stream, and that client side stream be represented by a server side stream that gets written (and its related database fetch) only when needed. In this case we would need some form of "state machine" that keeps running in the server and "knows" what is the next thing to fetch into the output stream when the client ask for more content. This technique is generally called a "continuation" and is nothing new in .NET, in fact using an IEnumerable<> interface and the "yield return" keyword does exactly that, so our first impulse might be to write our WebApi method more or less like this:           public IEnumerable<Metadata> Get([FromUri] int accountId)         {             // Execute the command and get a reader             using (var reader = GetMetadataListReader(accountId))             {                 // Read rows asynchronously, put data into buffer and write asynchronously                 while (reader.Read())                 {                     yield return MapRecord(reader);                 }             }         }   While the above method works, unfortunately it doesn't accomplish our objective of returning immediately to the caller, and that's because the MVC WebApi infrastructure doesn't yet recognize our intentions and when it finds an IEnumerable return value, enumerates it before returning to the client its values. To prove my point, I can code a test method that calls this method, for example:        [TestMethod]         public void StreamedDownload()         {             var baseUrl = @"http://localhost:57771/api/metadata/1";             var client = new HttpClient();             var sw = Stopwatch.StartNew();             var stream = client.GetStreamAsync(baseUrl).Result;             sw.Stop();             Debug.WriteLine("Elapsed time Call: {0}ms", sw.ElapsedMilliseconds); } So, I would expect the line "var stream = client.GetStreamAsync(baseUrl).Result" returns immediately without server-side fetching of all data in the database reader, and this didn't happened. To make the behavior more evident, you could insert a wait time (like Thread.Sleep(1000);) inside the "while" loop, and you will see that the client call (GetStreamAsync) is not going to return control after n seconds (being n == number of reader records being fetched).Ok, we know this doesn't work, and the question would be: is there a way to do it?Fortunately, YES!  and is not very difficult although a little more convoluted than our simple IEnumerable return value. Maybe in the future this scenario will be automatically detected and supported in MVC/WebApi.The solution to our needs is to use a very handy class named PushStreamContent and then our method signature needs to change to accommodate this, returning an HttpResponseMessage instead of our previously used IEnumerable<>. The final code will be something like this: public HttpResponseMessage Get([FromUri] int accountId)         {             HttpResponseMessage response = Request.CreateResponse();             // Create push content with a delegate that will get called when it is time to write out              // the response.             response.Content = new PushStreamContent(                 async (outputStream, httpContent, transportContext) =>                 {                     try                     {                         // Execute the command and get a reader                         using (var reader = GetMetadataListReader(accountId))                         {                             // Read rows asynchronously, put data into buffer and write asynchronously                             while (await reader.ReadAsync())                             {                                 var rec = MapRecord(reader);                                 var str = await JsonConvert.SerializeObjectAsync(rec);                                 var buffer = UTF8Encoding.UTF8.GetBytes(str);                                 // Write out data to output stream                                 await outputStream.WriteAsync(buffer, 0, buffer.Length);                             }                         }                     }                     catch(HttpException ex)                     {                         if (ex.ErrorCode == -2147023667) // The remote host closed the connection.                          {                             return;                         }                     }                     finally                     {                         // Close output stream as we are done                         outputStream.Close();                     }                 });             return response;         } As an extra bonus, all involved classes used already support async/await asynchronous execution model, so taking advantage of that was very easy. Please note that the PushStreamContent class receives in its constructor a lambda (specifically an Action) and we decorated our anonymous method with the async keyword (not a very well known technique but quite handy) so we can await over the I/O intensive calls we execute like reading from the database reader, serializing our entity and finally writing to the output stream.  Well, if we execute the test again we will immediately notice that the a line returns immediately and then the rest of the server code is executed only when the client reads through the obtained stream, therefore we get low memory usage and far greater scalability for our beloved application serving big chunks of data.Enjoy!Andrés.        

    Read the article

  • .NET Code Evolution

    - by Alois Kraus
    Originally posted on: http://geekswithblogs.net/akraus1/archive/2013/07/24/153504.aspxAt my day job I do look at a lot of code written by other people. Most of the code is quite good and some is even a masterpiece. And there is also code which makes you think WTF… oh it was written by me. Hm not so bad after all. There are many excuses reasons for bad code. Most often it is time pressure followed by not enough ambition (who cares) or insufficient training. Normally I do care about code quality quite a lot which makes me a (perceived) slow worker who does write many tests and refines the code quite a lot because of the design deficiencies. Most of the deficiencies I do find by putting my design under stress while checking for invariants. It does also help a lot to step into the code with a debugger (sometimes also Windbg). I do this much more often when my tests are red. That way I do get a much better understanding what my code really does and not what I think it should be doing. This time I do want to show you how code can evolve over the years with different .NET Framework versions. Once there was  time where .NET 1.1 was new and many C++ programmers did switch over to get rid of not initialized pointers and memory leaks. There were also nice new data structures available such as the Hashtable which is fast lookup table with O(1) time complexity. All was good and much code was written since then. At 2005 a new version of the .NET Framework did arrive which did bring many new things like generics and new data structures. The “old” fashioned way of Hashtable were coming to an end and everyone used the new Dictionary<xx,xx> type instead which was type safe and faster because the object to type conversion (aka boxing) was no longer necessary. I think 95% of all Hashtables and dictionaries use string as key. Often it is convenient to ignore casing to make it easy to look up values which the user did enter. An often followed route is to convert the string to upper case before putting it into the Hashtable. Hashtable Table = new Hashtable(); void Add(string key, string value) { Table.Add(key.ToUpper(), value); } This is valid and working code but it has problems. First we can pass to the Hashtable a custom IEqualityComparer to do the string matching case insensitive. Second we can switch over to the now also old Dictionary type to become a little faster and we can keep the the original keys (not upper cased) in the dictionary. Dictionary<string, string> DictTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); void AddDict(string key, string value) { DictTable.Add(key, value); } Many people do not user the other ctors of Dictionary because they do shy away from the overhead of writing their own comparer. They do not know that .NET has for strings already predefined comparers at hand which you can directly use. Today in the many core area we do use threads all over the place. Sometimes things break in subtle ways but most of the time it is sufficient to place a lock around the offender. Threading has become so mainstream that it may sound weird that in the year 2000 some guy got a huge incentive for the idea to reduce the time to process calibration data from 12 hours to 6 hours by using two threads on a dual core machine. Threading does make it easy to become faster at the expense of correctness. Correct and scalable multithreading can be arbitrarily hard to achieve depending on the problem you are trying to solve. Lets suppose we want to process millions of items with two threads and count the processed items processed by all threads. A typical beginners code might look like this: int Counter; void IJustLearnedToUseThreads() { var t1 = new Thread(ThreadWorkMethod); t1.Start(); var t2 = new Thread(ThreadWorkMethod); t2.Start(); t1.Join(); t2.Join(); if (Counter != 2 * Increments) throw new Exception("Hmm " + Counter + " != " + 2 * Increments); } const int Increments = 10 * 1000 * 1000; void ThreadWorkMethod() { for (int i = 0; i < Increments; i++) { Counter++; } } It does throw an exception with the message e.g. “Hmm 10.222.287 != 20.000.000” and does never finish. The code does fail because the assumption that Counter++ is an atomic operation is wrong. The ++ operator is just a shortcut for Counter = Counter + 1 This does involve reading the counter from a memory location into the CPU, incrementing value on the CPU and writing the new value back to the memory location. When we do look at the generated assembly code we will see only inc dword ptr [ecx+10h] which is only one instruction. Yes it is one instruction but it is not atomic. All modern CPUs have several layers of caches (L1,L2,L3) which try to hide the fact how slow actual main memory accesses are. Since cache is just another word for redundant copy it can happen that one CPU does read a value from main memory into the cache, modifies it and write it back to the main memory. The problem is that at least the L1 cache is not shared between CPUs so it can happen that one CPU does make changes to values which did change in meantime in the main memory. From the exception you can see we did increment the value 20 million times but half of the changes were lost because we did overwrite the already changed value from the other thread. This is a very common case and people do learn to protect their  data with proper locking.   void Intermediate() { var time = Stopwatch.StartNew(); Action acc = ThreadWorkMethod_Intermediate; var ar1 = acc.BeginInvoke(null, null); var ar2 = acc.BeginInvoke(null, null); ar1.AsyncWaitHandle.WaitOne(); ar2.AsyncWaitHandle.WaitOne(); if (Counter != 2 * Increments) throw new Exception(String.Format("Hmm {0:N0} != {1:N0}", Counter, 2 * Increments)); Console.WriteLine("Intermediate did take: {0:F1}s", time.Elapsed.TotalSeconds); } void ThreadWorkMethod_Intermediate() { for (int i = 0; i < Increments; i++) { lock (this) { Counter++; } } } This is better and does use the .NET Threadpool to get rid of manual thread management. It does give the expected result but it can result in deadlocks because you do lock on this. This is in general a bad idea since it can lead to deadlocks when other threads use your class instance as lock object. It is therefore recommended to create a private object as lock object to ensure that nobody else can lock your lock object. When you read more about threading you will read about lock free algorithms. They are nice and can improve performance quite a lot but you need to pay close attention to the CLR memory model. It does make quite weak guarantees in general but it can still work because your CPU architecture does give you more invariants than the CLR memory model. For a simple counter there is an easy lock free alternative present with the Interlocked class in .NET. As a general rule you should not try to write lock free algos since most likely you will fail to get it right on all CPU architectures. void Experienced() { var time = Stopwatch.StartNew(); Task t1 = Task.Factory.StartNew(ThreadWorkMethod_Experienced); Task t2 = Task.Factory.StartNew(ThreadWorkMethod_Experienced); t1.Wait(); t2.Wait(); if (Counter != 2 * Increments) throw new Exception(String.Format("Hmm {0:N0} != {1:N0}", Counter, 2 * Increments)); Console.WriteLine("Experienced did take: {0:F1}s", time.Elapsed.TotalSeconds); } void ThreadWorkMethod_Experienced() { for (int i = 0; i < Increments; i++) { Interlocked.Increment(ref Counter); } } Since time does move forward we do not use threads explicitly anymore but the much nicer Task abstraction which was introduced with .NET 4 at 2010. It is educational to look at the generated assembly code. The Interlocked.Increment method must be called which does wondrous things right? Lets see: lock inc dword ptr [eax] The first thing to note that there is no method call at all. Why? Because the JIT compiler does know very well about CPU intrinsic functions. Atomic operations which do lock the memory bus to prevent other processors to read stale values are such things. Second: This is the same increment call prefixed with a lock instruction. The only reason for the existence of the Interlocked class is that the JIT compiler can compile it to the matching CPU intrinsic functions which can not only increment by one but can also do an add, exchange and a combined compare and exchange operation. But be warned that the correct usage of its methods can be tricky. If you try to be clever and look a the generated IL code and try to reason about its efficiency you will fail. Only the generated machine code counts. Is this the best code we can write? Perhaps. It is nice and clean. But can we make it any faster? Lets see how good we are doing currently. Level Time in s IJustLearnedToUseThreads Flawed Code Intermediate 1,5 (lock) Experienced 0,3 (Interlocked.Increment) Master 0,1 (1,0 for int[2]) That lock free thing is really a nice thing. But if you read more about CPU cache, cache coherency, false sharing you can do even better. int[] Counters = new int[12]; // Cache line size is 64 bytes on my machine with an 8 way associative cache try for yourself e.g. 64 on more modern CPUs void Master() { var time = Stopwatch.StartNew(); Task t1 = Task.Factory.StartNew(ThreadWorkMethod_Master, 0); Task t2 = Task.Factory.StartNew(ThreadWorkMethod_Master, Counters.Length - 1); t1.Wait(); t2.Wait(); Counter = Counters[0] + Counters[Counters.Length - 1]; if (Counter != 2 * Increments) throw new Exception(String.Format("Hmm {0:N0} != {1:N0}", Counter, 2 * Increments)); Console.WriteLine("Master did take: {0:F1}s", time.Elapsed.TotalSeconds); } void ThreadWorkMethod_Master(object number) { int index = (int) number; for (int i = 0; i < Increments; i++) { Counters[index]++; } } The key insight here is to use for each core its own value. But if you simply use simply an integer array of two items, one for each core and add the items at the end you will be much slower than the lock free version (factor 3). Each CPU core has its own cache line size which is something in the range of 16-256 bytes. When you do access a value from one location the CPU does not only fetch one value from main memory but a complete cache line (e.g. 16 bytes). This means that you do not pay for the next 15 bytes when you access them. This can lead to dramatic performance improvements and non obvious code which is faster although it does have many more memory reads than another algorithm. So what have we done here? We have started with correct code but it was lacking knowledge how to use the .NET Base Class Libraries optimally. Then we did try to get fancy and used threads for the first time and failed. Our next try was better but it still had non obvious issues (lock object exposed to the outside). Knowledge has increased further and we have found a lock free version of our counter which is a nice and clean way which is a perfectly valid solution. The last example is only here to show you how you can get most out of threading by paying close attention to your used data structures and CPU cache coherency. Although we are working in a virtual execution environment in a high level language with automatic memory management it does pay off to know the details down to the assembly level. Only if you continue to learn and to dig deeper you can come up with solutions no one else was even considering. I have studied particle physics which does help at the digging deeper part. Have you ever tried to solve Quantum Chromodynamics equations? Compared to that the rest must be easy ;-). Although I am no longer working in the Science field I take pride in discovering non obvious things. This can be a very hard to find bug or a new way to restructure data to make something 10 times faster. Now I need to get some sleep ….

    Read the article

  • C# XP Sound QuickFix

    - by ikurtz
    I have this: ThreadPool.QueueUserWorkItem(new WaitCallback(FireAttackProc), fireResult); and FireAttackProc: private void FireAttackProc(Object stateInfo) { // Process Attack/Fire (local) lock (_procLock) { // build status message String status = "(Away vs. Home)"; // get Fire Result state info FireResult fireResult = (FireResult)stateInfo; // update home grid with attack information GameModel.HomeCellStatusSet(fireResult.FireGridLocation, Cell.cellState.Lock); this.Invoke(new Action(delegate() { RefreshHomeGrid(); })); status = status + "(Attack Coordinate: (" + GameModel.alphaCoords(fireResult.FireGridLocation.Column) + "," + fireResult.FireGridLocation.Row + "))(Result: "; // play audio data if true if (audio) { String Letters; Stream stream; SoundPlayer player; Letters = GameModel.alphaCoords(fireResult.FireGridLocation.Column); stream = Properties.Resources.ResourceManager.GetStream("_" + Letters); player = new System.Media.SoundPlayer(stream); player.PlaySync(); Letters = fireResult.FireGridLocation.Row.ToString(); stream = Properties.Resources.ResourceManager.GetStream("__" + Letters); player = new System.Media.SoundPlayer(stream); player.PlaySync(); stream.Dispose(); player.Dispose(); } if (audio) { SoundPlayer fire = new SoundPlayer(Properties.Resources.fire); fire.PlaySync(); fire.Dispose(); } // deal with hit/miss switch (fireResult.Hit) { case true: this.Invoke(new Action(delegate() { GameModel.HomeCellStatusSet(fireResult.FireGridLocation, Cell.cellState.Hit); status = status + "(Hit)"; })); if (audio) { SoundPlayer hit = new SoundPlayer(Properties.Resources.firehit); hit.PlaySync(); hit.Dispose(); } break; case false: this.Invoke(new Action(delegate() { GameModel.HomeCellStatusSet(fireResult.FireGridLocation, Cell.cellState.Miss); status = status + "(Miss)"; })); GameModel.PlayerNextTurn = NietzscheBattleshipsGameModel.GamePlayers.Home; if (audio) { SoundPlayer miss = new SoundPlayer(Properties.Resources.firemiss); miss.PlaySync(); miss.Dispose(); } break; } // refresh home grid with updated data this.Invoke(new Action(delegate() { RefreshHomeGrid(); })); GameToolStripStatusLabel.Text = status + ")"; // deal with ship destroyed if (fireResult.ShipDestroyed) { status = status + "(Destroyed: " + GameModel.getShipDescription(fireResult.DestroyedShipType) + ")"; if (audio) { Stream stream; SoundPlayer player; stream = Properties.Resources.ResourceManager.GetStream("_home"); player = new System.Media.SoundPlayer(stream); player.PlaySync(); player.Dispose(); stream.Dispose(); string ShipID = fireResult.DestroyedShipType.ToString(); stream = Properties.Resources.ResourceManager.GetStream("_" + ShipID); player = new System.Media.SoundPlayer(stream); player.PlaySync(); player.Dispose(); stream.Dispose(); stream = Properties.Resources.ResourceManager.GetStream("_destroyed"); player = new System.Media.SoundPlayer(stream); player.PlaySync(); player.Dispose(); stream.Dispose(); } } // deal with win condition if (fireResult.Win) { if (audio) { Stream stream; SoundPlayer player; stream = Properties.Resources.ResourceManager.GetStream("_home"); player = new System.Media.SoundPlayer(stream); player.PlaySync(); player.Dispose(); stream = Properties.Resources.ResourceManager.GetStream("_loses"); player = new System.Media.SoundPlayer(stream); player.PlaySync(); player.Dispose(); } GameModel.gameContracts = new GameContracts(); } // update status message if (fireResult.Hit) { if (!fireResult.Win) { status = status + "(Turn: Away)"; LockGUIControls(); } } // deal with turn logic if (GameModel.PlayerNextTurn == NietzscheBattleshipsGameModel.GamePlayers.Home) { this.Invoke(new Action(delegate() { if (!fireResult.Win) { status = status + "(Turn: Home)"; AwayTableLayoutPanel.Enabled = true; } })); } // deal with win condition if (fireResult.Win) { this.Invoke(new Action(delegate() { status = status + "(Game: Home Loses)"; CancelToolStripMenuItem.Enabled = false; NewToolStripMenuItem.Enabled = true; LockGUIControls(); })); } // display completed status message GameToolStripStatusLabel.Text = status + ")"; } } The issue is this: Under Vista/win7 the sound clips in the FireAttackProc plays. But under XP the logic contained within FireAttackProc gets executed but none of the sound clips play. Is there a quick solution to this so the sound will play under XP? I ask for a quick solution because i am happy being able to execute fully in Vista/Win7 but would be great if there was a quick solution so it would be XP compitable also. Thank you.

    Read the article

  • Problem with cometd and jetty 6 / 7

    - by Ceilingfish
    Hi chaps, I'm trying to get started with cometd (http://cometd.org/) and jetty 6 or 7, but I seem to be having problems. I've got an ant script that packages my code up into a war with the cometd 1.1.1 binaries and jetty binaries that are appropriate to the version of jetty I deploy the war to (so 7.1.2.v20100523 binaries when I deploy to jetty 7.1.2.v20100523 and 6.1.24 when I deploy to 6.1.24). I first tried getting a setup with version 7.1.2.v20100523, but when I tried to deploy I got a very long stack trace sample of which is: 2010-05-26 15:32:12.906:WARN::Problem processing jar entry org/eclipse/jetty/util/MultiPartOutputStream.class java.io.IOException: Invalid resource at org.eclipse.jetty.util.resource.URLResource.getInputStream(URLResource.java:204) at org.eclipse.jetty.util.resource.JarResource.getInputStream(JarResource.java:113) at org.eclipse.jetty.annotations.AnnotationParser$2.processEntry(AnnotationParser.java:575) at org.eclipse.jetty.webapp.JarScanner.matched(JarScanner.java:152) at org.eclipse.jetty.util.PatternMatcher.matchPatterns(PatternMatcher.java:82) at org.eclipse.jetty.util.PatternMatcher.match(PatternMatcher.java:64) at org.eclipse.jetty.webapp.JarScanner.scan(JarScanner.java:75) at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:587) at org.eclipse.jetty.annotations.AbstractConfiguration.parseWebInfLib(AbstractConfiguration.java:107) at org.eclipse.jetty.annotations.AnnotationConfiguration.configure(AnnotationConfiguration.java:68) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:992) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:579) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:381) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55) at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:36) at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:182) at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:497) at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:135) at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileChanged(ScanningAppProvider.java:77) at org.eclipse.jetty.util.Scanner.reportChange(Scanner.java:490) at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:355) at org.eclipse.jetty.util.Scanner.scan(Scanner.java:306) at org.eclipse.jetty.util.Scanner$1.run(Scanner.java:258) at java.util.TimerThread.mainLoop(Timer.java:512) at java.util.TimerThread.run(Timer.java:462) 2010-05-26 15:32:12.907:WARN::Problem processing jar entry org/eclipse/jetty/util/MultiPartWriter.class java.io.IOException: Invalid resource at org.eclipse.jetty.util.resource.URLResource.getInputStream(URLResource.java:204) at org.eclipse.jetty.util.resource.JarResource.getInputStream(JarResource.java:113) at org.eclipse.jetty.annotations.AnnotationParser$2.processEntry(AnnotationParser.java:575) at org.eclipse.jetty.webapp.JarScanner.matched(JarScanner.java:152) at org.eclipse.jetty.util.PatternMatcher.matchPatterns(PatternMatcher.java:82) at org.eclipse.jetty.util.PatternMatcher.match(PatternMatcher.java:64) at org.eclipse.jetty.webapp.JarScanner.scan(JarScanner.java:75) at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:587) at org.eclipse.jetty.annotations.AbstractConfiguration.parseWebInfLib(AbstractConfiguration.java:107) at org.eclipse.jetty.annotations.AnnotationConfiguration.configure(AnnotationConfiguration.java:68) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:992) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:579) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:381) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55) at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:36) at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:182) at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:497) at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:135) at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileChanged(ScanningAppProvider.java:77) at org.eclipse.jetty.util.Scanner.reportChange(Scanner.java:490) at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:355) at org.eclipse.jetty.util.Scanner.scan(Scanner.java:306) at org.eclipse.jetty.util.Scanner$1.run(Scanner.java:258) at java.util.TimerThread.mainLoop(Timer.java:512) at java.util.TimerThread.run(Timer.java:462) 2010-05-26 15:32:12.907:WARN::Problem processing jar entry org/eclipse/jetty/util/Attributes.class java.io.IOException: Invalid resource at org.eclipse.jetty.util.resource.URLResource.getInputStream(URLResource.java:204) at org.eclipse.jetty.util.resource.JarResource.getInputStream(JarResource.java:113) at org.eclipse.jetty.annotations.AnnotationParser$2.processEntry(AnnotationParser.java:575) at org.eclipse.jetty.webapp.JarScanner.matched(JarScanner.java:152) at org.eclipse.jetty.util.PatternMatcher.matchPatterns(PatternMatcher.java:82) at org.eclipse.jetty.util.PatternMatcher.match(PatternMatcher.java:64) at org.eclipse.jetty.webapp.JarScanner.scan(JarScanner.java:75) at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:587) at org.eclipse.jetty.annotations.AbstractConfiguration.parseWebInfLib(AbstractConfiguration.java:107) at org.eclipse.jetty.annotations.AnnotationConfiguration.configure(AnnotationConfiguration.java:68) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:992) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:579) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:381) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55) at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:36) at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:182) at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:497) at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:135) at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileChanged(ScanningAppProvider.java:77) at org.eclipse.jetty.util.Scanner.reportChange(Scanner.java:490) at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:355) at org.eclipse.jetty.util.Scanner.scan(Scanner.java:306) at org.eclipse.jetty.util.Scanner$1.run(Scanner.java:258) at java.util.TimerThread.mainLoop(Timer.java:512) at java.util.TimerThread.run(Timer.java:462) Seemed to go through all the jetty binaries and complain about each class file. When I tried to deploy to 6.1.24 I got org.mortbay.util.MultiException[java.lang.NoClassDefFoundError: org/eclipse/jetty/util/ajax/JSON$Source, java.lang.NoClassDefFoundError: org/eclipse/jetty/util/thread/ThreadPool] at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:656) at org.mortbay.jetty.servlet.Context.startContext(Context.java:140) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130) at org.mortbay.jetty.Server.doStart(Server.java:224) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.xml.XmlConfiguration.main(XmlConfiguration.java:985) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.mortbay.start.Main.invokeMain(Main.java:194) at org.mortbay.start.Main.start(Main.java:534) at org.mortbay.start.Main.start(Main.java:441) at org.mortbay.start.Main.main(Main.java:119) My web.xml looks like this: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>cometd</servlet-name> <servlet-class>org.cometd.server.continuation.ContinuationCometdServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>cometd</servlet-name> <url-pattern>/cometd/*</url-pattern> </servlet-mapping> <servlet> <servlet-name>initializer</servlet-name> <servlet-class>uk.co.dubit.nexus.comet.BayeuxInitializer</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <!-- <filter> <filter-name>cross-origin</filter-name> <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class> </filter> <filter-mapping> <filter-name>cross-origin</filter-name> <url-pattern>/cometd/*</url-pattern> </filter-mapping> --> </web-app> note cross origin filter is commented out. The class didn't seem to exist when I tried to run on 6.1.24 (which as far as I understand is the correct behaviour, yes?). Sorry for the noob question but does anyone know what I'm doing wrong here? Regards, Tom

    Read the article

< Previous Page | 5 6 7 8 9