Search Results

Search found 8588 results on 344 pages for 'thread abort'.

Page 73/344 | < Previous Page | 69 70 71 72 73 74 75 76 77 78 79 80  | Next Page >

  • Help with chat server

    - by mithun1538
    I am designing a chat server in java. The communication is Http based and not socket based. In the client side I have an applet. In the server side I have a servlet. Applet: I create a new thread to listen for incoming messages(GET method). The main thread is used to send messages(POST messages). The partial code is : public void start() { System.out.println("Creating new thread"); Thread thread = new Thread(this); thread.start(); } private String getNewMessage() { System.out.println("Inside getNewMessage"); String msg = null; try { while(msg == null) { System.out.println("Trying to listen to servlet"); URL servlet = new URL(getCodeBase(), "NewServlet?mode=msg"); URLConnection con = servlet.openConnection(); con.setUseCaches(false); DataInputStream din = new DataInputStream(new BufferedInputStream(con.getInputStream())); msg = din.readUTF(); System.out.println("message read :" + msg); } } catch (Exception e) { e.printStackTrace(); } return msg + "\n"; } public void run() { System.out.println("Inside new thread"); while(true) { System.out.println("inside first while"); String newMsg = getNewMessage(); chatOutput.append(newMsg); System.out.println("Appended!!"); } } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String message = chatInput.getText(); chatInput.setText(""); chatOutput.append(message + "\n"); try { System.out.println("Trying to send msg :" + message); URL url = new URL(getCodeBase(), "NewServlet"); URLConnection servletConnection = url.openConnection(); servletConnection.setDoInput(true); servletConnection.setDoOutput(true); servletConnection.setUseCaches(false); servletConnection.setRequestProperty("Content-Type", "application/octet-stream"); ObjectOutputStream out = new ObjectOutputStream(servletConnection.getOutputStream()); out.writeObject(message); out.flush(); out.close(); System.out.println("Message sent!"); } catch (Exception e) { e.printStackTrace(); } } This next code is from the servlet side. it uses the Observable interface to identify and send messages to clients. public class NewServlet extends HttpServlet { // getNextMessage() returns the next new message. // It blocks until there is one. public String getNextMessage() { // Create a message sink to wait for a new message from the // message source. System.out.println("inside getNextMessage"); return new MessageSink().getNextMessage(source);} @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Inside Doget"); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println(getNextMessage()); } // broadcastMessage() informs all currently listening clients that there // is a new message. Causes all calls to getNextMessage() to unblock. public void broadcastMessage(String message) { // Send the message to all the HTTP-connected clients by giving the // message to the message source source.sendMessage(message); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Inside DoPost"); try { ObjectInputStream din= new ObjectInputStream(request.getInputStream()); String message = (String)din.readObject(); System.out.println("received msg"); if (message != null) broadcastMessage(message); System.out.println("Called broadcast"); // Set the status code to indicate there will be no response response.setStatus(response.SC_NO_CONTENT); } catch (Exception e) { e.printStackTrace(); } } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; } MessageSource source = new MessageSource();} class MessageSource extends Observable { public void sendMessage(String message) { System.out.println("inside sendMsg"); setChanged(); notifyObservers(message); } } class MessageSink implements Observer { String message = null; // set by update() and read by getNextMessage() // Called by the message source when it gets a new message synchronized public void update(Observable o, Object arg) { // Get the new message message = (String)arg; // Wake up our waiting thread notify(); } // Gets the next message sent out from the message source synchronized public String getNextMessage(MessageSource source) { // Tell source we want to be told about new messages source.addObserver(this); System.out.println("AddedObserver"); // Wait until our update() method receives a message while (message == null) { try { wait(); } catch (Exception ignored) { } } // Tell source to stop telling us about new messages source.deleteObserver(this); // Now return the message we received // But first set the message instance variable to null // so update() and getNextMessage() can be called again. String messageCopy = message; message = null; System.out.println("Returning msg"); return messageCopy; } } As you can see I have included System.out.println("Some message"); in some places. this was just for debugging purposes. In java console, i get the following output: Creating new thread Inside new thread. inside first while. Inside getNewMessage. Trying to listen to servlet. In the servlet side, i get the following output in the tomcat logs: Inside Doget. inside getNextMessage. AddedObserver. After i type a message in the applet, and send it, I get the foll output in java console: Trying to send msg :you deR?? Message sent! But in servlet side, I dont get anything in the logs. I used the O'Reily Java Servlet Programming as reference(The observer interface comes from there). But I am not getting any chat communication between two clients. As can be understood from the logs, the POST method is not called. Any reason for this?

    Read the article

  • Why can't Perl's DBD::DB2 find dbivport.h during installation?

    - by Liju Mathew
    We are using a Perl utility to dump data from DB2 database. We installed DBI package and it is asking for DBD package also. We dont have root access and when we try to install DBD package we are getting the following error: ERROR BUILDING DB2.pm [lijumathew@intblade03 DBD-DB2-1.78]$ make make[1]: Entering directory '/home/lijumathew/lperl/perlsrc/DBD-DB2-1.78/Constants' gcc -c -I"/db2/db2tf1/sqllib/include" -D_REENTRANT -D_GNU_SOURCE -DDEBUGGING -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/usr/include/gdbm -O2 -g -pipe -m32 -march=i386 -mtune=pentium4 -DVERSION=\"1.78\" -DXS_VERSION=\"1.78\" -fPIC "-I/usr/lib/perl5/5.8.5/i386-linux-thread-multi/CORE" Constants.c Running Mkbootstrap for DBD::DB2::Constants () chmod 644 Constants.bs rm -f ../blib/arch/auto/DBD/DB2/Constants/Constants.so gcc -shared -L/usr/local/lib Constants.o -o ../blib/arch/auto/DBD/DB2/Constants/Constants.so chmod 755 ../blib/arch/auto/DBD/DB2/Constants/Constants.so cp Constants.bs ../blib/arch/auto/DBD/DB2/Constants/Constants.bs chmod 644 ../blib/arch/auto/DBD/DB2/Constants/Constants.bs make[1]: Leaving directory `/home/lijumathew/lperl/perlsrc/DBD-DB2-1.78/Constants' gcc -c -I"/db2/db2tf1/sqllib/include" -I"/usr/lib/perl5/site_perl/5.8.5/i386-linux-thread-multi/auto/DBI" -I"/usr/lib/perl5/5.8.5/i386-linux-thread-multi/auto/DBI" -I"/usr/lib/perl5/vendor_perl/5.8.5/i386-linux-thread-multi/auto/DBI" -I"/usr/lib/perl5/site_perl/5.8.5/i386-linux-thread-multi/auto/DBI" -D_REENTRANT -D_GNU_SOURCE -DDEBUGGING -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/usr/include/gdbm -O2 -g -pipe -m32 -march=i386 -mtune=pentium4 -DVERSION=\"1.78\" -DXS_VERSION=\"1.78\" -fPIC "-I/usr/lib/perl5/5.8.5/i386-linux-thread-multi/CORE" DB2.c In file included from DB2.h:22, from DB2.xs:7: dbdimp.h:10:22: dbivport.h: No such file or directory make: *** [DB2.o] Error 1 How do we fix this? Do we need root access to resolve this?

    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

  • ASP.NET Setting Culture with InitializeCulture

    - by Helen
    I have a website with three domains .com, .de and .it Each domain needs to default to the local language/culture of the country. I have created a base page and added an InitializeCulture Protected Overrides Sub InitializeCulture() Dim url As System.Uri = Request.Url Dim hostname As String = url.Host.ToString() Dim SelectedLanguage As String If HttpContext.Current.Profile("PreferredCulture").ToString Is Nothing Then Select Case hostname Case "www.domain.de" SelectedLanguage = "de" Thread.CurrentThread.CurrentUICulture = New CultureInfo(SelectedLanguage) Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(SelectedLanguage) Case "www.domain.it" SelectedLanguage = "it" Thread.CurrentThread.CurrentUICulture = New CultureInfo(SelectedLanguage) Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(SelectedLanguage) Case Else SelectedLanguage = "en" Thread.CurrentThread.CurrentUICulture = New CultureInfo(SelectedLanguage) Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(SelectedLanguage) End Select End If End Sub This is fine. The problem now occurs because we also want three language selection buttons on the home page so that the user can override the domain language. So on my Default.asp.vb we have three button events like this... Protected Sub langEnglish_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles langEnglish.Click Dim SelectedLanguage As String = "en" 'Save selected user language in profile HttpContext.Current.Profile.SetPropertyValue("PreferredCulture", SelectedLanguage) 'Force re-initialization of the page to fire InitializeCulture() Context.Server.Transfer(Context.Request.Path) End Sub But of course the InititalizeCulture then overrides whatever button selection has been made. Is there any way that the InitialCulture can check whether a button click has occurred and if so skip the routine? Any advice would be greatly appreciated, thanks.

    Read the article

  • DBI::DBD package not getting installed for Perl?

    - by Liju Mathew
    Hi, We are using a Perl utility to dump data from DB2 database. We installed DBI package and it is asking for DBD package also. We dont have root access and when we try to install DBD package we are getting the following error. ERROR BUILDING DB2.pm [lijumathew@intblade03 DBD-DB2-1.78]$ make make[1]: Entering directory '/home/lijumathew/lperl/perlsrc/DBD-DB2-1.78/Constants' gcc -c -I"/db2/db2tf1/sqllib/include" -D_REENTRANT -D_GNU_SOURCE -DDEBUGGING -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/usr/include/gdbm -O2 -g -pipe -m32 -march=i386 -mtune=pentium4 -DVERSION=\"1.78\" -DXS_VERSION=\"1.78\" -fPIC "-I/usr/lib/perl5/5.8.5/i386-linux-thread-multi/CORE" Constants.c Running Mkbootstrap for DBD::DB2::Constants () chmod 644 Constants.bs rm -f ../blib/arch/auto/DBD/DB2/Constants/Constants.so gcc -shared -L/usr/local/lib Constants.o -o ../blib/arch/auto/DBD/DB2/Constants/Constants.so chmod 755 ../blib/arch/auto/DBD/DB2/Constants/Constants.so cp Constants.bs ../blib/arch/auto/DBD/DB2/Constants/Constants.bs chmod 644 ../blib/arch/auto/DBD/DB2/Constants/Constants.bs make[1]: Leaving directory `/home/lijumathew/lperl/perlsrc/DBD-DB2-1.78/Constants' gcc -c -I"/db2/db2tf1/sqllib/include" -I"/usr/lib/perl5/site_perl/5.8.5/i386-linux-thread-multi/auto/DBI" -I"/usr/lib/perl5/5.8.5/i386-linux-thread-multi/auto/DBI" -I"/usr/lib/perl5/vendor_perl/5.8.5/i386-linux-thread-multi/auto/DBI" -I"/usr/lib/perl5/site_perl/5.8.5/i386-linux-thread-multi/auto/DBI" -D_REENTRANT -D_GNU_SOURCE -DDEBUGGING -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/usr/include/gdbm -O2 -g -pipe -m32 -march=i386 -mtune=pentium4 -DVERSION=\"1.78\" -DXS_VERSION=\"1.78\" -fPIC "-I/usr/lib/perl5/5.8.5/i386-linux-thread-multi/CORE" DB2.c In file included from DB2.h:22, from DB2.xs:7: dbdimp.h:10:22: dbivport.h: No such file or directory make: *** [DB2.o] Error 1 How to fix this? Do we need root access to resolve this? Appreciate the help in advance. Thanks, Mathew Liju

    Read the article

  • Can I tell Castle Windsor to create a component in a separate AppDomain?

    - by Michael L Perry
    I've created a multi-threaded service that uses Castle Windsor to create components to run on separate threads. I Resolve an component by name with parameters for each thread. I'm running into concurrency problems with a 3rd party library used by the components. I suspect that isolating those components in separate AppDomains will resolve the problem. Is there a way to have Resolve create the component using a different AppDomain? private ActivityThread NewActivityThread(ActivityInstance activityInstance) { // Set up the creation arguments. System.Collections.IDictionary arguments = new Dictionary<string, string>(); activityInstance.Parameters.ForEach(p => arguments.Add(p.Name, p.Value)); // Get the activity handler from the container. IActivity activity = Program.Container.Resolve<IActivity>(activityInstance.Name, arguments); // Create a thread for the activity. ActivityThread thread = new ActivityThread(activity, activityInstance, _nextActivityID++); return thread; } public ActivityThread(IActivity activity, ActivityInstance instance, int id) { _activity = activity; _instance = instance; _id = id; } public void Start() { if (_thread == null) { // Create a new thread to run this activity. _thread = new Thread(delegate() { _activity.Run(); }); _thread.Name = _activity.ToString(); _thread.SetApartmentState(ApartmentState.STA); _thread.Start(); } }

    Read the article

  • Do the ‘up to date’ guarantees for values of Java's final fields extend to indirect references?

    - by mattbh
    The Java language spec defines semantics of final fields in section 17.5: The usage model for final fields is a simple one. Set the final fields for an object in that object's constructor. Do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are. My question is - does the 'up-to-date' guarantee extend to the contents of nested arrays, and nested objects? An example scenario: Thread A constructs a HashMap of ArrayLists, then assigns the HashMap to final field 'myFinal' in an instance of class 'MyClass' Thread B sees a (non-synchronized) reference to the MyClass instance and reads 'myFinal', and accesses and reads the contents of one of the ArrayLists In this scenario, are the members of the ArrayList as seen by Thread B guaranteed to be at least as up to date as they were when MyClass's constructor completed? I'm looking for clarification of the semantics of the Java Memory Model and language spec, rather than alternative solutions like synchronization. My dream answer would be a yes or no, with a reference to the relevant text.

    Read the article

  • boost bind callback function pointer as a parameter

    - by Takashi-kun
    I am trying to pass a function pointer using boost::bind. void Class::ThreadFunction(Type(*callbackFunc)(message_type::ptr&)) { } boost::shared_ptr<boost::thread> Class::Init(Type(*callbackFunc)(message_type::ptr&)) { return boost::shared_ptr<boost::thread> ( new boost::thread(boost::bind(&Class::ThreadFunction, callbackFunc)) ); } I get the following errors: 1>C:\dev\sapphire\boost_1_46_1\boost/bind/mem_fn.hpp(362) : warning C4180: qualifier applied to function type has no meaning; ignored 1>C:\dev\sapphire\boost_1_46_1\boost/bind/mem_fn.hpp(333) : error C2296: '->*' : illegal, left operand has type 'Type (__cdecl **)(message_type::ptr &)' However, I was able to change to the following, it works fine: void ThreadFunction(Type(*callbackFunc)(message_type::ptr&)) { } boost::shared_ptr<boost::thread> Class::Init(Type(*callbackFunc)(message_type::ptr&)) { return boost::shared_ptr<boost::thread> ( new boost::thread(boost::bind(&ThreadFunction, callbackFunc)) ); } Why do I get those errors if I declare the method in the Class class?

    Read the article

  • NPTL Default Stack Size Problem

    - by eyazici
    Hello, I am developing a multithread modular application using C programming language and NPTL 2.6. For each plugin, a POSIX thread is created. The problem is each thread has its own stack area, since default stack size depends on user's choice, this may results in huge memory consumption in some cases. To prevent unnecessary memory usage I used something similar to this to change stack size before creating each thread: pthread_attr_t attr; pthread_attr_init (&attr); pthread_attr_getstacksize(&attr, &st1); if(pthread_attr_setstacksize (&attr, MODULE_THREAD_SIZE) != 0) perror("Stack ERR"); pthread_attr_getstacksize(&attr, &st2); printf("OLD:%d, NEW:%d - MIN: %d\n", st1, st2, PTHREAD_STACK_MIN); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); /* "this" is static data structure that stores plugin related data */ pthread_create(&this->runner, &attr, (void *)(void *)this->run, NULL); EDIT I: pthread_create() section added. This did not work work as I expected, the stack size reported by pthread_attr_getstacksize() is changed but total memory usage of the application (from ps/top/pmap output) did not changed: OLD:10485760, NEW:65536 - MIN: 16384 When I use ulimit -s MY_STACK_SIZE_LIMIT before starting application I achieve the expected result. My questions are: 1-) Is there any portable(between UNIX variants) way to change (default)thread stack size after starting application(before creating thread of course)? 2-) Is it possible to use same stack area for every thread? 3-) Is it possible completely disable stack for threads without much pain?

    Read the article

  • C# Communication between threads.

    - by GT
    Hi, I am using .NET 3.5 and am trying to wrap my head around a problem (not being a supreme threading expert bear with me). I have a windows service which has a very intensive process that is always running, I have put this process onto a separate thread so that the main thread of my service can handle operational tasks - i.e., service audit cycles, handling configuration changes, etc, etc. I'm starting the thread via the typical ThreadStart to a method which kicks the process off - call it workerthread. On this workerthread I am sending data to another server, as is expected the server reboots every now and again and connection is lost and I need to re-establish the connection (I am notified by the lost of connection via an event). From here I do my reconnect logic and I am back in and running, however what I easily started to notice to happen was that I was creating this worker thread over and over again each time (not what I want). Now I could kill the workerthread when I lose the connection and start a new one but this seems like a waste of resources. What I really want to do, is marshal the call (i.e., my thread start method) back to the thread that is still in memory although not doing anything. Please post any examples or docs you have that would be of use. Thanks.

    Read the article

  • Calculate time of method execution and send to WCF service async

    - by Tim
    I need to implement time calculation for repository methods in my asp .net mvc project classes. The problem is that i need to send time calculation data to WCF Service which is time consuming. I think about threads which can help to cal WCF service asynchronously. But I have very little experience with it. Do I need to create new thread each time or I can create a global thread, if so then how? I have something like that: StopWatch class public class StopWatch { private DateTime _startTime; private DateTime _endTime; public void Start() { _startTime = DateTime.Now; } protected void StopTimerAndWriteStatistics() { _endTime = DateTime.Now; TimeSpan timeResult = _endTime - _startTime; //WCF proxy object var reporting = AppServerUtility.GetProxy<IReporting>(); //Send data to server reporting.WriteStatistics(_startTime, _endTime, timeResult, "some information"); } public void Stop() { //Here is the thread I have question with var thread = new Thread(StopTimerAndWriteStatistics); thread.Start(); } } Using of StopWatch class in Repository public class SomeRepository { public List<ObjectInfo> List() { StopWatch sw = new StopWatch(); sw.Start(); //performing long time operation sw.Stop(); } } What am I doing wrong with threads?

    Read the article

  • Java Memory Model: reordering and concurrent locks

    - by Steffen Heil
    Hi The java meomry model mandates that synchronize blocks that synchronize on the same monitor enforce a before-after-realtion on the variables modified within those blocks. Example: // in thread A synchronized( lock ) { x = true; } // in thread B synchronized( lock ) { System.out.println( x ); } In this case it is garanteed that thread B will see x==true as long as thread A already passed that synchronized-block. Now I am in the process to rewrite lots of code to use the more flexible (and said to be faster) locks in java.util.concurrent, especially the ReentrantReadWriteLock. So the example looks like this: // in thread A synchronized( lock ) { lock.writeLock().lock(); x = true; lock.writeLock().unlock(); } // in thread B synchronized( lock ) { lock.readLock().lock(); System.out.println( x ); lock.readLock().unlock(); } However, I have not seen any hints within the memory model specification that such locks also imply the nessessary ordering. Looking into the implementation it seems to rely on the access to volatile variables inside AbstractQueuedSynchronizer (for the sun implementation at least). However this is not part of any specification and moreover access to non-volatile variables is not really condsidered covered by the memory barrier given by these variables, is it? So, here are my questions: Is it safe to assume the same ordering as with the "old" synchronized blocks? Is this documented somewhere? Is accessing any volatile variable a memory barrier for any other variable? Regards, Steffen

    Read the article

  • WPF: UnauthorizedAccessException using anonymous methods.

    - by Diego Pacheco Pedemonte
    Here is the thing, I want to create a simply app that copy many files from one site, and move them to another; but using async methods and create a new thread. private void button3_Click(object sender, RoutedEventArgs e) { //progressBar1.Maximum = _FileInfoArray.Count; DispatcherTimer dt1 = new DispatcherTimer(); foreach (FileInfo Fi in _FileInfoArray) { Thread t = new Thread(new ThreadStart(delegate() { DispatcherOperation _dispOp = progressBar1.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(delegate() { File.Copy(txtdestino.Text, Fi.FullName, true); //progressBar1.Value = n; //txtstatus.Content = ("Copiados " + n.ToString() + " archivos"); //Thread.Sleep(100); } )); _dispOp.Completed += new EventHandler(_dispOp_Completed); } )); t.Start(); } } UnauthorizedAccessException is throw! It says that I can't access to txtdestino content. Some clues? -------------------------------------------------------------------------------Edited This is the version with all the changes, get the same error :( any clues? private void button4_Click(object sender, RoutedEventArgs e) { //First: Build mynames List<string> mynames = new List<string>(); foreach (FileInfo fi in _FileInfoArray) { mynames.Add(fi.FullName); } Thread t = new Thread(new ThreadStart(delegate() { foreach (string fullname in mynames) { DispatcherOperation _dispOp = progressBar1.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(delegate() { string destino = System.IO.Path.Combine(@"C:\", System.IO.Path.GetFileName(fullname)); File.Copy(fullname, destino, true); //Some progressbar changes } )); _dispOp.Completed += new EventHandler(_dispOp_Completed); } } )); t.Start(); } File.Copy(txtdestino.Text, Fi.FullName, true); // here the exception is throw

    Read the article

  • best practice for directory polling

    - by Hieu Lam
    Hi all, I have to do batch processing to automate business process. I have to poll directory at regular interval to detect new files and do processing. While old files is being processed, new files can come in. For now, I use quartz scheduler and thread synchronization to ensure that only one thread can process files. Part of the code are: application-context.xml <bean id="methodInvokingJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" <property name="targetObject" ref="documentProcessor" / <property name="targetMethod" value="processDocuments" / </bean DocumentProcessor ..... public void processDocuments() { LOG.info(Thread.currentThread().getName() + " attempt to run."); if (!processing) { synchronized (this) { try { processing = true; LOG.info(Thread.currentThread().getName() + " is processing"); List xmlDocuments = documentManager.getFileNamesFromFolder(incomingFolderPath); // loop over the files and processed unlock files. for (String xmlDocument : xmlDocuments) { processDocument(xmlDocument); } } finally { processing = false; } } } } For the current code, I have to prevent other thread to process files when one thread is processing. Is that a good idea ? or we support multi-threaded processing. In that case how can I know which files is being process and which files has just arrived ? Any idea is really appreciated.

    Read the article

  • POSIX AIO Library and Callback Handlers

    - by Charles Salvia
    According to the documentation on aio_read/write, there are basically 2 ways that the AIO library can inform your application that an async file I/O operation has completed. Either 1) you can use a signal, 2) you can use a callback function I think that callback functions are vastly preferable to signals, and would probably be much easier to integrate into higher-level multi-threaded libraries. Unfortunately, the documentation for this functionality is a mess to say the least. Some sources, such as the man page for the sigevent struct, indicate that you need to set the sigev_notify data member in the sigevent struct to SIGEV_CALLBACK and then provide a function handler. Presumably, the handler is invoked in the same thread. Other documentation indicates you need to set sigev_notify to SIGEV_THREAD, which will invoke the callback handler in a newly created thread. In any case, on my Linux system (Ubuntu with a 2.6.28 kernel) SIGEV_CALLBACK doesn't seem to be defined anywhere, but SIGEV_THREAD works as advertised. Unfortunately, creating a new thread to invoke the callback handler seems really inefficient, especially if you need to invoke many handlers. It would be better to use an existing pool of threads, similar to the way most network I/O event demultiplexers work. Some versions of UNIX, such as QNX, include a SIGEV_SIGNAL_THREAD flag, which allows you to invoke handlers using a specified existing thread, but this doesn't seem to be available on Linux, nor does it seem to even be a part of the POSIX standard. So, is it possible to use the POSIX AIO library in a way that invokes user handlers in a pre-allocated background thread/threadpool, rather than creating/destroying a new thread everytime a handler is invoked?

    Read the article

  • Java: does the EDT restart or not when an exception is thrown?

    - by NoozNooz42
    (the example code below is self-contained and runnable, you can try it, it won't crash your system :) Tom Hawtin commented on the question here: http://stackoverflow.com/questions/3018165 that: It's unlikely that the EDT would crash. Unchecked exceptions thrown in EDT dispatch are caught, dumped and the thread goes on. Can someone explain me what is going on here (every time you click on the "throw an unchecked exception" button, a divide by zero is performed, on purpose): import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class CrashEDT extends JFrame { public static void main(String[] args) { final CrashEDT frame = new CrashEDT(); frame.addWindowListener(new WindowAdapter() { public void windowClosing( WindowEvent e) { System.exit(0); } }); final JButton jb = new JButton( "throw an unchecked exception" ); jb.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { System.out.println( "Thread ID:" + Thread.currentThread().getId() ); System.out.println( 0 / Math.abs(0) ); } } ); frame.add( jb ); frame.setSize(300, 150); frame.setVisible(true); } } I get the following message (which is what I'd expect): Exception in thread "AWT-EventQueue-0" java.lang.ArithmeticException: / by zero and to me this is an unchecked exception right? You can see that the thread ID is getting incremented every time you trigger the crash. So is the EDT automatically restarted every time an unchecked exception is thrown or are unchecked exceptions "caught, dumped and the thread goes on" like Tom Hawtin commented? What is going on here?

    Read the article

  • LWUIT Deadlock (lwuit dialog VS System dialog)

    - by Ramps
    Hi, I have a deadlock problem when I try to make some I/O operations that needs user permission. When user click the button I start a new thread which is responsible for performing IO operations, and I display lwuit "please wait" dialog. Dialog is dismissed by IO thread from callback method. Problem is that, when system dialog appears (asking for user permission ) on top of lwuit dialog - deadlock occurs. I assume that this is because dialog.show() method blocks main thread (EDT), so it's impossible to dismiss system dialog, when lwuit dialog is behind it. Anyone managed to solve this problem? Here is the simplified code, hope it is clear enough: protected void actionPerformed(ActionEvent evt, int id) { switch (id) { case ID_FRIEND: MyRunnableWithIoOperation r = new MyRunnableWithIoOperation(this); new Thread(r).start(); //run the thread performing IO operations Command cmd = mWaitDialog.showDialog(); // show the "please wait" dialog ...//handle cancel }//end switch } /* method called from MyRunnableWithIoOperation, when operation finished*/ public void myCallbackMethod(){ mWaitDialog.dispose(); // } I tried to start my IO thread by calling Display.getInstance().invokeAndBlock( r ), but with no luck. In such case, my "wait dialog" doesn't show up.

    Read the article

  • Syncronization Exception

    - by Kurru
    Hi I have two threads, one thread processes a queue and the other thread adds stuff into the queue. I want to put the queue processing thread to sleep when its finished processing the queue I want to have the 2nd thread tell it to wake up when it has added an item to the queue However these functions call System.Threading.SynchronizationLockException: Object synchronization method was called from an unsynchronized block of code on the Monitor.PulseAll(waiting); call, because I havent syncronized the function with the waiting object. [which I dont want to do, i want to be able to process while adding items to the queue]. How can I achieve this? Queue<object> items = new Queue<object>(); object waiting = new object(); 1st Thread public void ProcessQueue() { while (true) { if (items.Count == 0) Monitor.Wait(waiting); object real = null; lock(items) { object item = items.Dequeue(); real = item; } if(real == null) continue; .. bla bla bla } } 2nd Thread involves public void AddItem(object o) { ... bla bla bla lock(items) { items.Enqueue(o); } Monitor.PulseAll(waiting); }

    Read the article

  • Seeking help with a MT design pattern

    - by SamG
    I have a queue of 1000 work items and a n-proc machine (assume n = 4).The main thread spawns n (=4) worker threads at a time ( 25 outer iterations) and waits for all threads to complete before processing the next n (=4) items until the entire queue is processed for(i= 0 to queue.Length / numprocs) for(j= 0 to numprocs) { CreateThread(WorkerThread,WorkItem) } WaitForMultipleObjects(threadHandle[]) The work done by each (worker) thread is not homogeneous.Therefore in 1 batch (of n) if thread 1 spends 1000 s doing work and rest of the 3 threads only 1 s , above design is inefficient,becaue after 1 sec other 3 processors are idling. Besides there is no pooling - 1000 distinct threads are being created How do I use the NT thread pool (I am not familiar enough- hence the long winded question) and QueueUserWorkitem to achieve the above. The following constraints should hold The main thread requires that all worker items are processed before it can proceed.So I would think that a waitall like construct above is required I want to create as many threads as processors (ie not 1000 threads at a time) Also I dont want to create 1000 distinct events, pass to the worker thread, and wait on all events using the QueueUserWorkitem API or otherwise Exisitng code is in C++.Prefer C++ because I dont know c# I suspect that the above is a very common pattern and was looking for input from you folks.

    Read the article

  • Run time error in java servlet

    - by Derk
    The build of the project is succesfull, but when I go the the url I get the following error report: >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 instantiating servlet class example.servlet.ScrapingServlet org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) java.lang.Thread.run(Thread.java:619) >root cause java.lang.NoClassDefFoundError: org/apache/http/impl/client/DefaultHttpClient java.lang.Class.getDeclaredConstructors0(Native Method) java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) java.lang.Class.getConstructor0(Class.java:2699) java.lang.Class.newInstance0(Class.java:326) java.lang.Class.newInstance(Class.java:308) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) java.lang.Thread.run(Thread.java:619) >root cause java.lang.ClassNotFoundException: org.apache.http.impl.client.DefaultHttpClient org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1358) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204) java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) java.lang.Class.getDeclaredConstructors0(Native Method) java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) java.lang.Class.getConstructor0(Class.java:2699) java.lang.Class.newInstance0(Class.java:326) java.lang.Class.newInstance(Class.java:308) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) java.lang.Thread.run(Thread.java:619) >note The full stack trace of the root cause is available in the Apache Tomcat/6.0.14 logs. Apache Tomcat/6.0.14 And that is because I added this simple line to the code: HttpClient httpclient = new DefaultHttpClient(); What am I doing wrong?

    Read the article

  • Writing to a log4net FileAppender with multiple threads performance problems

    - by Wayne
    TickZoom is a very high performance app which uses it's own parallelization library and multiple O/S threads for smooth utilization of multi-core computers. The app hits a bottleneck where users need to write information to a LogAppender from separate O/S threads. The FileAppender uses the MinimalLock feature so that each thread can lock and write to the file and then release it for the next thread to write. If MinimalLock gets disabled, log4net reports errors about the file being already locked by another process (thread). A better way for log4net to do this would be to have a single thread that takes care of writing to the FileAppender and any other threads simply add their messages to a queue. In that way, MinimalLock could be disabled to greatly improve performance of logging. Additionally, the application does a lot of CPU intensive work so it will also improve performance to use a separate thread for writing to the file so the CPU never waits on the I/O to complete. So the question is, does log4net already offer this feature? If so, how do you do enable threaded writing to a file? Is there another, more advanced appender, perhaps? If not, then since log4net is already wrapped in the platform, that makes it possible to implement a separate thread and queue for this purpose in the TickZoom code. Sincerely, Wayne

    Read the article

  • There's a black hole in my server (TcpClient, TcpListener)

    - by Matías
    Hi, I'm trying to build a server that will receive files sent by clients over a network. If the client decides to send one file at a time, there's no problem, I get the file as I expected, but if it tries to send more than one I only get the first one. Here's the server code: I'm using one Thread per connected client public void ProcessClients() { while (IsListening) { ClientHandler clientHandler = new ClientHandler(listener.AcceptTcpClient()); Thread thread = new Thread(new ThreadStart(clientHandler.Process)); thread.Start(); } } The following code is part of ClientHandler class public void Process() { while (client.Connected) { using (MemoryStream memStream = new MemoryStream()) { int read; while ((read = client.GetStream().Read(buffer, 0, buffer.Length)) > 0) { memStream.Write(buffer, 0, read); } if (memStream.Length > 0) { Packet receivedPacket = (Packet)Tools.Deserialize(memStream.ToArray()); File.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Guid.NewGuid() + receivedPacket.Filename), receivedPacket.Content); } } } } On the first iteration I get the first file sent, but after it I don't get anything. I've tried using a Thread.Sleep(1000) at the end of every iteration without any luck. On the other side I have this code (for clients) . . client.Connect(); foreach (var oneFilename in fileList) client.Upload(oneFilename); client.Disconnect(); . . The method Upload: public void Upload(string filename) { FileInfo fileInfo = new FileInfo(filename); Packet packet = new Packet() { Filename = fileInfo.Name, Content = File.ReadAllBytes(filename) }; byte[] serializedPacket = Tools.Serialize(packet); netStream.Write(serializedPacket, 0, serializedPacket.Length); netStream.Flush(); } netStream (NetworkStream) is opened on Connect method, and closed on Disconnect. Where's the black hole? Can I send multiple objects as I'm trying to do? Thanks for your time.

    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

  • java.lang.NoClassDefFoundError

    - by Jenny
    Everything was working just fine but now I can no longer run my application. For some reason javax.* is not being found yet in Eclipse the imports are fine... exception javax.servlet.ServletException: Error allocating a servlet instance org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) java.lang.Thread.run(Thread.java:619) root cause java.lang.NoClassDefFoundError: javax/servlet/http/HttpServlet java.lang.ClassLoader.defineClass1(Native Method) java.lang.ClassLoader.defineClassCond(ClassLoader.java:632) java.lang.ClassLoader.defineClass(ClassLoader.java:616) java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) java.net.URLClassLoader.defineClass(URLClassLoader.java:283) java.net.URLClassLoader.access$000(URLClassLoader.java:58) java.net.URLClassLoader$1.run(URLClassLoader.java:197) java.security.AccessController.doPrivileged(Native Method) java.net.URLClassLoader.findClass(URLClassLoader.java:190) java.lang.ClassLoader.loadClass(ClassLoader.java:307) sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) java.lang.ClassLoader.loadClass(ClassLoader.java:248) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1560) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) java.lang.Thread.run(Thread.java:619) root cause java.lang.ClassNotFoundException: javax.servlet.http.HttpServlet java.net.URLClassLoader$1.run(URLClassLoader.java:202) java.security.AccessController.doPrivileged(Native Method) java.net.URLClassLoader.findClass(URLClassLoader.java:190) java.lang.ClassLoader.loadClass(ClassLoader.java:307) sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) java.lang.ClassLoader.loadClass(ClassLoader.java:248) java.lang.ClassLoader.defineClass1(Native Method) java.lang.ClassLoader.defineClassCond(ClassLoader.java:632) java.lang.ClassLoader.defineClass(ClassLoader.java:616) java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) java.net.URLClassLoader.defineClass(URLClassLoader.java:283) java.net.URLClassLoader.access$000(URLClassLoader.java:58) java.net.URLClassLoader$1.run(URLClassLoader.java:197) java.security.AccessController.doPrivileged(Native Method) java.net.URLClassLoader.findClass(URLClassLoader.java:190) java.lang.ClassLoader.loadClass(ClassLoader.java:307) sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) java.lang.ClassLoader.loadClass(ClassLoader.java:248) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1560) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) java.lang.Thread.run(Thread.java:619)

    Read the article

  • Application doesn't exit with 0 threads

    - by Bryce Wagner
    We have a WinForms desktop application, which is heavily multithreaded. 3 threads run with Application.Run and a bunch of other background worker threads. Getting all the threads to shut down properly was kind of tricky, but I thought I finally got it right. But when we actually deployed the application, users started experiencing the application not exiting. There's a System.Threading.Mutex to prevent them from running the app multiple times, so they have to go into task manager and kill the old one before they can run it again. Every thread gets a Thread.Join before the main thread exits, and I added logging to each thread I spawn. According to the log, every single thread that starts also exits, and the main thread also exits. Even stranger, running SysInternals ProcessExplorer show all the threads disappear when the application exits. As in, there are 0 threads (managed or unmanaged), but the process is still running. I can't reproduce this on any developers computers or our test environment, and so far I've only seen it happen on Windows XP (not Vista or Windows 7 or any Windows Server). How can a process keep running with 0 threads?

    Read the article

< Previous Page | 69 70 71 72 73 74 75 76 77 78 79 80  | Next Page >