Search Results

Search found 3641 results on 146 pages for 'threads'.

Page 19/146 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • WebLogic Server Performance and Tuning: Part II - Thread Management

    - by Gokhan Gungor
    WebLogic Server, like any other java application server, provides resources so that your applications use them to provide services. Unfortunately none of these resources are unlimited and they must be managed carefully. One of these resources is threads which are pooled to provide better throughput and performance along with the fast response time and to avoid deadlocks. Threads are execution points that WebLogic Server delivers its power and execute work. Managing threads is very important because it may affect the overall performance of the entire system. In previous releases of WebLogic Server 9.0 we had multiple execute queues and user defined thread pools. There were different queues for different type of work which had fixed number of execute threads.  Tuning of this thread pools and finding the proper number of threads was time consuming which required many trials. WebLogic Server 9.0 and the following releases use a single thread pool and a single priority-based execute queue. All type of work is executed in this single thread pool. Its size (thread count) is automatically decreased or increased (self-tuned). The new “self-tuning” system simplifies getting the proper number of threads and utilizing them.Work manager allows your applications to run concurrently in multiple threads. Work manager is a mechanism that allows you to manage and utilize threads and create rules/guidelines to follow when assigning requests to threads. We can set a scheduling guideline or priority a request with a work manager and then associate this work manager with one or more applications. At run-time, WebLogic Server uses these guidelines to assign pending work/requests to execution threads. The position of a request in the execute queue is determined by its priority. There is a default work manager that is provided. The default work manager should be sufficient for most applications. However there can be cases you want to change this default configuration. Your application(s) may be providing services that need mixture of fast response time and long running processes like batch updates. However wrong configuration of work managers can lead a performance penalty while expecting improvement.We can define/configure work managers at;•    Domain Level: config.xml•    Application Level: weblogic-application.xml •    Component Level: weblogic-ejb-jar.xml or weblogic.xml(For a specific web application use weblogic.xml)We can use the following predefined rules/constraints to manage the work;•    Fair Share Request Class: Specifies the average thread-use time required to process requests. The default is 50.•    Response Time Request Class: Specifies a response time goal in milliseconds.•    Context Request Class: Assigns request classes to requests based on context information.•    Min Threads Constraint: Limits the number of concurrent threads executing requests.•    Max Threads Constraint: Guarantees the number of threads the server will allocate to requests.•    Capacity Constraint: Causes the server to reject requests only when it has reached its capacity. Let’s create a work manager for our application for a long running work.Go to WebLogic console and select Environment | Work Managers from the domain structure tree. Click New button and select Work manager and click next. Enter the name for the work manager and click next. Then select the managed server instances(s) or clusters from available targets (the one that your long running application is deployed) and finish. Click on MyWorkManager, and open the Configuration tab and check Ignore Stuck Threads and save. This will prevent WebLogic to tread long running processes (that is taking more than a specified time) as stuck and enable to finish the process.

    Read the article

  • Assigning a property across threads

    - by Mike
    I have set a property across threads before and I found this post http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the-t about getting a property. I think my issue with the code below is setting the variable to the collection is an object therefore on the heap and therefore is just creating a pointer to the same object So my question is besides creating a deep copy, or copying the collection into a different List object is there a better way to do the following to aviod the error during the for loop. Cross-thread operation not valid: Control 'lstProcessFiles' accessed from a thread other than the thread it was created on. Code: private void btnRunProcess_Click(object sender, EventArgs e) { richTextBox1.Clear(); BackgroundWorker bg = new BackgroundWorker(); bg.DoWork += new DoWorkEventHandler(bg_DoWork); bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted); bg.RunWorkerAsync(lstProcessFiles.SelectedItems); } void bg_DoWork(object sender, DoWorkEventArgs e) { WorkflowEngine engine = new WorkflowEngine(); ListBox.SelectedObjectCollection selectedCollection=null; if (lstProcessFiles.InvokeRequired) { // Try #1 selectedCollection = (ListBox.SelectedObjectCollection) this.Invoke(new GetSelectedItemsDelegate(GetSelectedItems), new object[] { lstProcessFiles }); // Try #2 //lstProcessFiles.Invoke( // new MethodInvoker(delegate { // selectedCollection = lstProcessFiles.SelectedItems; })); } else { selectedCollection = lstProcessFiles.SelectedItems; } // *********Same Error on this line******************** // Cross-thread operation not valid: Control 'lstProcessFiles' accessed // from a thread other than the thread it was created on. foreach (string l in selectedCollection) { if (engine.LoadProcessDocument(String.Format(@"C:\TestDirectory\{0}", l))) { try { engine.Run(); WriteStep(String.Format("Ran {0} Succussfully", l)); } catch { WriteStep(String.Format("{0} Failed", l)); } engine.PrintProcess(); WriteStep(String.Format("Rrinted {0} to debug", l)); } } } private delegate void WriteDelegate(string p); private delegate ListBox.SelectedObjectCollection GetSelectedItemsDelegate(ListBox list); private ListBox.SelectedObjectCollection GetSelectedItems(ListBox list) { return list.SelectedItems; }

    Read the article

  • Synchronization of Nested Data Structures between Threads in Java

    - by Dominik
    I have a cache implementation like this: class X { private final Map<String, ConcurrentMap<String, String>> structure = new HashMap...(); public String getValue(String context, String id) { // just assume for this example that there will be always an innner map final ConcurrentMap<String, String> innerStructure = structure.get(context); String value = innerStructure.get(id); if(value == null) { synchronized(structure) { // can I be sure, that this inner map will represent the last updated // state from any thread? value = innerStructure.get(id); if(value == null) { value = getValueFromSomeSlowSource(id); innerStructure.put(id, value); } } } return value; } } Is this implementation thread-safe? Can I be sure to get the last updated state from any thread inside the synchronized block? Would this behaviour change if I use a java.util.concurrent.ReentrantLock instead of a synchronized block, like this: ... if(lock.tryLock(3, SECONDS)) { try { value = innerStructure.get(id); if(value == null) { value = getValueFromSomeSlowSource(id); innerStructure.put(id, value); } } finally { lock.unlock(); } } ... I know that final instance members are synchronized between threads, but is this also true for the objects held by these members? Maybe this is a dumb question, but I don't know how to test it to be sure, that it works on every OS and every architecture.

    Read the article

  • Cannot run a JUnit test case containing threads from Eclipse

    - by Parag
    I am running JUnit test case from Eclipse 3.4.1 . This test case creates a class which starts a thread to do some stuff. When the test method ends it seems that Eclipse is forcibly shutting down the thread. If I run the same test from the command line, then the thread runs properly. Somehow I do not remember running into such problems with Eclipse before. Is this something that was always present in Eclipse or did they add it in 3.4.x ? Here is an example: When I run this test from Eclipse, I get a few printts of the cnt (till about 1800) and then the test case is terminated utomatically. However, if I run the main method, which starts JUnit's TestRunner, then the thread counts indefinetely. import junit.framework.TestCase; import junit.textui.TestRunner; /** * This class shows that Eclipses JUnit test case runner will forcibly * terminate all running threads * * @author pshah * */ public class ThreadTest extends TestCase { static Runnable run = new Runnable() { public void run() { int cnt = 0; while(true) System.out.println(cnt++); } }; public void testThread() { Thread t = new Thread(run); t.start(); } public static void main(String args[]) { TestRunner runner = new TestRunner(); runner.run(ThreadTest.class); } }

    Read the article

  • Best practices for Java logging from multiple threads?

    - by Jason S
    I want to have a diagnostic log that is produced by several tasks managing data. These tasks may be in multiple threads. Each task needs to write an element (possibly with subelements) to the log; get in and get out quickly. If this were a single-task situation I'd use XMLStreamWriter as it seems like the best match for simplicity/functionality without having to hold a ballooning XML document in memory. But it's not a single-task situation, and I'm not sure how to best make sure this is "threadsafe", where "threadsafe" in this application means that each log element should be written to the log correctly and serially (one after the other and not interleaved in any way). Any suggestions? I have a vague intuition that the way to go is to use a queue of log elements (with each one able to be produced quickly: my application is busy doing real work that's performance-sensitive), and have a separate thread which handles the log elements and sends them to a file so the logging doesn't interrupt the producers. The logging doesn't necessarily have to be XML, but I do want it to be structured and machine-readable. edit: I put "threadsafe" in quotes. Log4j seems to be the obvious choice (new to me but old to the community), why reinvent the wheel...

    Read the article

  • Multiple threads modifying a collection in Java??

    - by posdef
    Hi, The project I am working on requires a whole bunch of queries towards a database. In principle there are two types of queries I am using: read from excel file, check for a couple of parameters and do a query for hits in the database. These hits are then registered as a series of custom classes. Any hit may (and most likely will) occur more than once so this part of the code checks and updates the occurrence in a custom list implementation that extends ArrayList. for each hit found, do a detail query and parse the output, so that the classes created in (I) get detailed info. I figured I would use multiple threads to optimize time-wise. However I can't really come up with a good way to solve the problem that occurs with the collection these items are stored in. To elaborate a little bit; throughout the execution objects are supposed to be modified by both (I) and (II). I deliberately didn't c/p any code, as it would be big chunks of code to make any sense.. I hope it make some sense with the description above. Thanks,

    Read the article

  • Java problem with multiple threads when executing a runnable jar file

    - by Spi1988
    I have developed a Java Swing application, which uses the SwingWorker class to perform some long running tasks. When the application is run from the IDE (Netbeans), I can start multiple long running tasks simultaneously without any problem. I created a runnable jar file for the application, in order to be able to run it from outside the IDE. The application when run from this jar file works well with the only exception that it doesn't allow me to start 2 long running tasks simultaneously. When I start the first task (assume it takes 2 minitues to complete), every thing works fine, the UI does not freeze (it never freezes). However, when I try to run another task (assume it takes just 10 seconds, therefore it should finish before the first task) while the first task has not yet completed, nothing seems to happen. In reality, the second task would have started, and also finished its processing, however its results are only displayed once the first task completes. I dunno why this is happening. Is there some restriction on the number of threads which could run simultaneously on the JVM? Are there any jvm arguments which i could try to solve this problem. I hope i explained my problem well. Thanks in advance, Peter Bartolo

    Read the article

  • How does static code run with multiple threads?

    - by Krisc
    I was reading http://stackoverflow.com/questions/1511798/threading-from-within-a-class-with-static-and-non-static-methods and I am in a similar situation. I have a static method that pulls data from a resource and creates some runtime objects based on the data. static class Worker{ public static MyObject DoWork(string filename){ MyObject mo = new MyObject(); // ... does some work return mo; } } The method takes awhile (in this case it is reading 5-10mb files) and returns an object. I want to take this method and use it in a multiple thread situation so I can read multiple files at once. Design issues / guidelines aside, how would multiple threads access this code? Let's say I have something like this... class ThreadedWorker { public void Run() { Thread t = new Thread(OnRun); t.Start(); } void OnRun() { MyObject mo = Worker.DoWork("somefilename"); mo.WriteToConsole(); } } Does the static method run for each thread, allowing for parallel execution?

    Read the article

  • how to close a java frame with threads

    - by user261002
    I have a java frame that I want to close it automatically after 3 or 4 seconds. I found out I must used threads. but I dont know how exactly to do it, this a dumy part of my code : package intro; import java.awt.*; import java.io.IOException; //import view.LangMenu; public class IntroClass extends Frame { private int _screenWidth = 0; private int _screenHeight = 0; private int _screenCenterx = 0; private int _screenCentery = 0; //private static final String SOUND_PATH="/sounds/introSound.midi"; public IntroClass() { Toolkit thisScreen = Toolkit.getDefaultToolkit(); Dimension thisScrrensize = thisScreen.getScreenSize(); _screenWidth = thisScrrensize.width; _screenHeight = thisScrrensize.height; _screenCenterx = _screenWidth / 2; _screenCentery = _screenHeight / 2; setBackground(Color.pink); Label lbl = new Label("Welcome To Dots Game. Samaneh Khaleghi", Label.CENTER); add(lbl); setUndecorated(true); setLocation((_screenCenterx*50)/100,_screenCentery-(_screenCentery*50)/100); setSize((_screenWidth * 50) / 100, (_screenHeight * 50) / 100); WaitClass r = new WaitClass(); r.start(); view.DotsBoardFrame d=new view.DotsBoardFrame(); main.Main.showScreen(d); } class WaitClass extends Thread { boolean running = true; public void run() { while (running) { try { Thread.sleep(50); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } }

    Read the article

  • Java threads, wait time always 00:00:00-Producer/Consumer

    - by user3742254
    I am currently doing a producer consumer problem with a number of threads and have had to set priorities and waits to them to ensure that one thread, the security thread, runs last. I have managed to do this and I have managed to get the buffer working. The last thing that I am required to do is to show the wait time of threads that are too large for the buffer and to calculate the average wait time. I have included code to do so, but everything I run the program, the wait time is always returned as 00:00:00, and by extension, the average is returned as the same. I was speaking to one of my colleagues who said that it is not a matter of the code but rather a matter of the computer needing to work off of one processor, which can be adjusted in the task manager settings. He has an HP like myself but his program prints the wait time 180 times, whereas mine prints usually about 3-7 times and is only 00:00:01 on one instance before finishing when I have made the processor adjustments. My other colleague has an iMac and hers puts out an average of 42:00:34(42 minutes??) I am very confused about this because I can see no difference between our codes and like my colleague said, I was wondering is it a computer issue. I am obviously concerned as I wanted to make sure that my code correctly calculated an average wait time, but that is impossible to tell when the wait times always show as 00:00:00. To calculate the thread duration, including the time it entered and exited the buffer was done by using a timestamp import, and then subtracting start time from end time. Is my code correct for this issue or is there something which is missing? I would be very grateful for any solutions. Below is my code: My buffer class package com.Com813cw; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * Created by Rory on 10/08/2014. */ class Buffer { private int contents, count = 0, process = 200; private int totalRam = 1000; private boolean available = false; private long start, end, wait, request = 0; private DateFormat time = new SimpleDateFormat("ss:SSS"); public int avWaitTime =0; public void average(){ System.out.println("Average Application Request wait time: "+ time.format(request/count)); } public synchronized int get() { while (process <= 500) { try { wait(); } catch (InterruptedException e) { } } process -= 200; System.out.println("CPU After Process " + process); notifyAll(); return contents; } public synchronized void put(int value) { if (process <= 500) { process += value; } else { start = System.currentTimeMillis(); try { wait(); } catch (InterruptedException e) { } end = System.currentTimeMillis(); wait = end - start; count++; request += wait; System.out.println("Application Request Wait Time: " + time.format(wait)); process += value; contents = value; calcWait(wait, count); } notifyAll(); } public void calcWait(long wait, int count){ this.avWaitTime = (int) (wait/count); } public void printWait(){ System.out.println("Wait time is " + time.format(this.avWaitTime)); } } My spotify class package com.Com813cw; import java.sql.Timestamp; /** * Created by Rory on 11/08/2014. */ class Spotify extends Thread { private Buffer buffer; private int number; private int bytes = 250; public Spotify(Buffer c, int number) { buffer = c; this.number = number; } long startTime = System.currentTimeMillis(); public void run() { for (int i = 0; i < 20; i++) { buffer.put(bytes); System.out.println(getName() + this.number + " put: " + bytes + " bytes "); try { sleep(1000); } catch (InterruptedException e) { } } long endTime = System.currentTimeMillis(); long timeTaken = endTime - startTime; java.util.Date date = new java.util.Date(); System.out.println("-----------------------------"); System.out.println("Spotify has finished executing."); System.out.println("Time taken to execute was " + timeTaken + " milliseconds"); System.out.println("Time that Spotify thread exited Buffer was " + new Timestamp(date.getTime())); System.out.println("-----------------------------"); } } My BubbleWitch class package com.Com813cw; import java.lang.*; import java.lang.System; import java.sql.Timestamp; /** * Created by Rory on 10/08/2014. */ class BubbleWitch2 extends Thread { private Buffer buffer; private int number; private int bytes = 100; public BubbleWitch2(Buffer c, int number) { buffer = c; this.number=number ; } long startTime = System.currentTimeMillis(); public void run() { for (int i = 0; i < 10; i++) { buffer.put(bytes); System.out.println(getName() + this.number + " put: " + bytes + " bytes "); try { sleep(1000); } catch (InterruptedException e) { } } long endTime = System.currentTimeMillis(); long timeTaken = endTime - startTime; java.util.Date date = new java.util.Date(); System.out.println("-----------------------------"); System.out.println("BubbleWitch2 has finished executing."); System.out.println("Time taken to execute was " +timeTaken+ " milliseconds"); System.out.println("Time Bubblewitch2 thread exited Buffer was " + new Timestamp(date.getTime())); System.out.println("-----------------------------"); } } My Test class package com.Com813cw; /** * Created by Rory on 10/08/2014. */ public class ProducerConsumerTest { public static void main(String[] args) throws InterruptedException { Buffer c = new Buffer(); BubbleWitch2 p1 = new BubbleWitch2(c,1); Processor c1 = new Processor(c, 1); Spotify p2 = new Spotify(c, 2); SystemManagement p3 = new SystemManagement(c, 3); SecurityUpdate p4 = new SecurityUpdate(c, 4, p1, p2, p3); p1.setName("BubbleWitch2 "); p2.setName("Spotify "); p3.setName("System Management "); p4.setName("Security Update "); p1.setPriority(10); p2.setPriority(10); p3.setPriority(10); p4.setPriority(5); c1.start(); p1.start(); p2.start(); p3.start(); p4.start(); p2.join(); p3.join(); p4.join(); c.average(); System.exit(0); } } My security update package com.Com813cw; import java.lang.*; import java.lang.System; import java.sql.Timestamp; /** * Created by Rory on 11/08/2014. */ class SecurityUpdate extends Thread { private Buffer buffer; private int number; private int bytes = 150; private int process = 0; public SecurityUpdate(Buffer c, int number, BubbleWitch2 bubbleWitch2, Spotify spotify, SystemManagement systemManagement) throws InterruptedException { buffer = c; this.number = number; bubbleWitch2.join(); spotify.join(); systemManagement.join(); } long startTime = System.currentTimeMillis(); public void run() { for (int i = 0; i < 15; i++) { buffer.put(bytes); System.out.println(getName() + this.number + " put: " + bytes + " bytes"); try { sleep(1500); } catch (InterruptedException e) { } } long endTime = System.currentTimeMillis(); long timeTaken = endTime - startTime; java.util.Date date = new java.util.Date(); System.out.println("-----------------------------"); System.out.println("Security Update has finished executing."); System.out.println("Time taken to execute was " + timeTaken + " milliseconds"); System.out.println("Time that SecurityUpdate thread exited Buffer was " + new Timestamp(date.getTime())); System.out.println("------------------------------"); } } I'd be grateful as I said for any help as this is the last and most frustrating obstacle.

    Read the article

  • Java: design for using many executors services and only few threads

    - by Guillaume
    I need to run in parallel multiple threads to perform some tests. My 'test engine' will have n tests to perform, each one doing k sub-tests. Each test result is stored for a later usage. So I have n*k processes that can be ran concurrently. I'm trying to figure how to use the java concurrent tools efficiently. Right now I have an executor service at test level and n executor service at sub test level. I create my list of Callables for the test level. Each test callable will then create another list of callables for the subtest level. When invoked a test callable will subsequently invoke all subtest callables test 1 subtest a1 subtest ...1 subtest k1 test n subtest a2 subtest ...2 subtest k2 call sequence: test manager create test 1 callable test1 callable create subtest a1 to k1 testn callable create subtest an to kn test manager invoke all test callables test1 callable invoke all subtest a1 to k1 testn callable invoke all subtest an to kn This is working fine, but I have a lot of new treads that are created. I can not share executor service since I need to call 'shutdown' on the executors. My idea to fix this problem is to provide the same fixed size thread pool to each executor service. Do you think it is a good design ? Do I miss something more appropriate/simple for doing this ?

    Read the article

  • C#: Populating a UI using separate threads.

    - by Andrew
    I'm trying to make some sense out of an application Ive been handed in order to track down the source of an error. Theres a bit of code (simplified here) which creates four threads which in turn populate list views on the main form. Each method gets data from the database and retrieves graphics from a resource dll in order to directly populate an imagelist and listview. From what Ive read on here (link) updating UI elements from any thread other than the UI thread should not be done, and yet this appears to work? Thread t0 = new Thread(new ThreadStart(PopulateListView1)); t0.IsBackground = true; t0.Start(); Thread t1 = new Thread(new ThreadStart(PopulateListView2)); t1.Start(); Thread t2 = new Thread(new ThreadStart(PopulateListView3)); t2.Start(); Thread t3 = new Thread(new ThreadStart(PopulateListView4)); t3.Start(); The error itself is a System.InvalidOperationException "Image cannot be added to the ImageList." which has me wondering if the above code is linked in some way. Iis this method of populating the UI recommended and if not what are the possible complications resulting from it?

    Read the article

  • Error with threads during automatic testing on TeamCity 5

    - by yeyeyerman
    Hello, I'm having some problems executing the tests of the application I'm developing. All the tests execute normally with ReSharper and in NCover. However, the execution of one of these tests in TeamCity is generating an error. This test initializes two objects, the object under test and a simulator of a real object. Both objects will communicate throug a serial link in a representation of the real scenario. ObjectSimulator r_simulator = new ObjectSimulator(...); ObjectDriver r_driver = new ObjectDriver(...); Assert.IsTrue(r_driver.Connect() == ErrorCode.Success); The simulator just do the following in the constructor public class ObjectSimulator { ... public ObjectSimulator() { // serial port configuration m_port = new SerialPort(); m_port.DataReceived += DataReceivedEvent; } ... } The main object has two threads. The main thread of the application and a timer to refresh a watchdog timer in the real object. public ErrorCode Connect() { ... StartSynchroTimer(); Thread.Sleep(4); // to check if the timer is working properly ... } The problem is comming from the Thread.Sleep() call, as when I remove it everything works. It seems like the ObjectSimulator also sleeps and doesn't receive the DataReceived event. How can I resolve this issue?

    Read the article

  • Equvalent c++0x program withought using boost threads..

    - by Eternal Learner
    I have the below simple program using boost threads, what would be the changes needed to do the same in c++0X #include<iostream> #include<boost/thread/thread.hpp> boost::mutex mutex; struct count { count(int i): id(i){} void operator()() { boost::mutex::scoped_lock lk(mutex); for(int i = 0 ; i < 10000 ; i++) { std::cout<<"Thread "<<id<<"has been called "<<i<<" Times"<<std::endl; } } private: int id; }; int main() { boost::thread thr1(count(1)); boost::thread thr2(count(2)); boost::thread thr3(count(3)); thr1.join(); thr2.join(); thr3.join(); return 0; }

    Read the article

  • java threads don't see shared boolean changes

    - by andymur
    Here the code class Aux implements Runnable { private Boolean isOn = false; private String statusMessage; private final Object lock; public Aux(String message, Object lock) { this.lock = lock; this.statusMessage = message; } @Override public void run() { for (;;) { synchronized (lock) { if (isOn && "left".equals(this.statusMessage)) { isOn = false; System.out.println(statusMessage); } else if (!isOn && "right".equals(this.statusMessage)) { isOn = true; System.out.println(statusMessage); } if ("left".equals(this.statusMessage)) { System.out.println("left " + isOn); } } } } } public class Question { public static void main(String [] args) { Object lock = new Object(); new Thread(new Aux("left", lock)).start(); new Thread(new Aux("right", lock)).start(); } } In this code I expect to see: left, right, left right and so on, but when Thread with "left" message changes isOn to false, Thread with "right" message don't see it and I get ("right true" and "left false" console messages), left thread don't get isOn in true, but right Thread can't change it cause it always see old isOn value (true). When i add volatile modifier to isOn nothing changes, but if I change isOn to some class with boolean field and change this field then threads are see changes and it works fine Thanks in advance.

    Read the article

  • Help with java threads or executors: Executing several MySQL selects, inserts and updates simmultane

    - by Martin
    Hi. I'm writing an application to analyse a MySQL database, and I need to execute several DMLs simmultaneously; for example: // In ResultSet rsA: Select * from A; rsA.beforeFirst(); while (rsA.next()) { id = rsA.getInt("id"); // Retrieve data from table B: Select * from B where B.Id=" + id; // Crunch some numbers using the data from B // Close resultset B } I'm declaring an array of data objects, each with its own Connection to the database, which in turn calls several methods for the data analysis. The problem is all threads use the same connection, thus all tasks throw exceptios: "Lock wait timeout exceeded; try restarting transaction" I believe there is a way to write the code in such a way that any given object has its own connection and executes the required tasks independent from any other object. For example: DataObject dataObject[0] = new DataObject(id[0]); DataObject dataObject[1] = new DataObject(id[1]); DataObject dataObject[2] = new DataObject(id[2]); ... DataObject dataObject[N] = new DataObject(id[N]); // The 'DataObject' class has its own connection to the database, // so each instance of the object should use its own connection. // It also has a "run" method, which contains all the tasks required. Executor ex = Executors.newFixedThreadPool(10); for(i=0;i<=N;i++) { ex.execute(dataObject[i]); } // Here where the problem is: Each instance creates a new connection, // but every DML from any of the objects is cluttered in just one connection // (in MySQL command line, "SHOW PROCESSLIST;" throws every connection, and all but // one are idle). Can you point me in the right direction? Thanks

    Read the article

  • OpenGL multiple threads, variable handling [closed]

    - by toeplitz
    I have written an OpenGL program which runs in the following way: Main: - Initialize SDL - Create thread which has the OpenGL context: - Renderloop - Set camera (view) matrix with glUniform. - glDrawElements() .... etc. - Swapbuffers(); - Main SDL loop handling input events and such. - Update camera matrix of type glm::mat4. This is how I pass my camera object to the class that handles opengl. Camera *cam = new Camera(); gl.setCam(cam); where void setCam(Camera *camera) { this->camera = camera; } For rendering in the opengl context thread, this happens: glm::mat4 modelView = camera->view * model; glUniformMatrix4fv(shader->bindUniform("modelView"), 1, GL_FALSE, glm::value_ptr(modelView)); In the main program where my SDL and other things are handles I then recompute the view matrix. This his working fine without me using any mutex locks. Is this correct? On the other hand, I add objects to my scene by an "upload queue" and in this case I have to mutex lock my upload queue vector (vector class type) when adding items to it or else the program crashes. In summary: I recompute my matrix in a different thread and then use it in the opengl thread without any mutex lock. Why is this working? Edit: I think my question is similar to what was asked here: Should I lock a variable in one thread if I only need it's value in other threads, and why does it work if I don't?, only in my case it is even more simple with only one matrix being changed.

    Read the article

  • passing pipe to threads

    - by alaamh
    I see it's easy to open pipe between two process using fork, but how we can passing open pipe to threads. Assume we need to pass out of PROGRAM A to PROGRAM B "may by more than one thread", PROGRAM B send his output to PROGRAM C #include <stdio.h> #include <stdlib.h> #include <pthread.h> struct targ_s { int fd_reader; }; void *thread1(void *arg) { struct targ_s *targ = (struct targ_s*) arg; int status, fd[2]; pid_t pid; pipe(fd); pid = fork(); if (pid == 0) { dup2(STDIN_FILENO, targ->fd_reader); close(fd[0]); dup2(fd[1], STDOUT_FILENO); close(fd[1]); execvp ("PROGRAM B", NULL); exit(1); } else { close(fd[1]); dup2(fd[0], STDIN_FILENO); close(fd[0]); execl("PROGRAM C", NULL); wait(&status); return NULL; } } int main(void) { FILE *fpipe; char *command = "PROGRAM A"; char buffer[1024]; if (!(fpipe = (FILE*) popen(command, "r"))) { perror("Problems with pipe"); exit(1); } char* outfile = "out.dat"; FILE* f = fopen (outfile, "wb"); int fd = fileno( f ); struct targ_s targ; targ.fd_reader = fd; pthread_t thid; if (pthread_create(&thid, NULL, thread1, &targ) != 0) { perror("pthread_create() error"); exit(1); } int len; while (read(fpipe, buffer, sizeof (buffer)) != 0) { len = strlen(buffer); write(fd, buffer, len); } pclose(fpipe); return (0); }

    Read the article

  • Proper way to Dispose of a BackGroundWorker

    - by galford13x
    Would this be a proper way to dispose of a BackGroundWorker? I'm not sure if it is necesary to remove the events before calling .Dispose(). Also is calling .Dispose() inside the RunWorkerCompleted delegate ok to do? public void RunProcessAsync(DateTime dumpDate) { BackgroundWorker worker = new BackgroundWorker(); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerAsync(dumpDate); } void worker_DoWork(object sender, DoWorkEventArgs e) { // Do Work here } void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; worker.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); worker.DoWork -= new DoWorkEventHandler(worker_DoWork); worker.Dispose(); }

    Read the article

  • C++ _beginthreadex in cygwin

    - by Hugh
    Hello all, I am aware that _beginthreadex is part of the MSCVRT functions and therefore not accessible via Cygwin/MinGW uintptr_t _beginthreadex( void *security, unsigned stack_size, unsigned ( __stdcall *start_address )( void * ), void *arglist, unsigned initflag, unsigned *thrdaddr ); However, _beginthreadex does call upon CreateThread(). HANDLE CreateThread( LPSECURITY_ATTRIBUTES secAttr, SIZE_T stackSize, LPTHREAD_START_ROUTINE threadFunc, LPVOID param, DWORD flags, LPDWORD threadID ); However, does anyone have a wrapper or a URL to a library that is compatible with Cygwin/WinGW. Or can offer some advice? As this is the last little piece of moving from VSutdio Project over to makefiles for Windows/Darwin/Linux. Thanks.

    Read the article

  • Show form that showDialog from mainForm won't block it, but closing mainForm will close it

    - by meme
    how yo show a form which needs to run synchronously. I tried running application.run from a queueworker of a threadpool- but I had some invalid handles sometime. tried using a regular thread but then when main form closes it doesn't close this- and I don't really like the idea of killing the thread on_formclosing. if I use form.show it's fine besides that fact that any showdialog from the main form will block also this. What's the best way to handle this?

    Read the article

  • Async BinaryWriter ?

    - by blez
    I found implementation of async BinaryWriter here: http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/11f6aa76-1383-4cab-8693-29dcb25bbf2e But I can't really use it. I change all my types to AsyncBinaryWriter and I use .Write, but no data is written to the stream. Is that the proper way for using it ?

    Read the article

  • ScoreNinja causes java.lang.RuntimeException: Can't create handler inside thread that has not called

    - by sirconnorstack
    I'm trying to add ScoreNinja, the global high score system, to my Android game, and it works fine when I load it on my phone, but when I release it into the wild, I got crash reports saying: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() Here is part of the call stack: android.os.Handler.<init>(Handler.java:121) android.app.Dialog.<init>(Dialog.java:99) android.app.AlertDialog.<init>(AlertDialog.java:65) android.app.AlertDialog.<init>(AlertDialog.java:61) android.app.AlertDialog$Builder.create(AlertDialog.java:797) android.app.AlertDialog$Builder.show(AlertDialog.java:812) com.scoreninja.adapter.ScoreNinjaAdapter.show(ScoreNinjaAdapter.java:136) com.scoreninja.adapter.ScoreNinjaAdapter.show(ScoreNinjaAdapter.java:99) I thought the main thread had prepare() called automatically, and if not, why would it work fine for me but not anyone else?

    Read the article

  • Java SwingWorker still uses 98% CPU after it's done.

    - by RemiX
    I am new to the Java SwingWorker class, but I'm trying to get it to do some stuff in the background. That part works already, but now, when it is finished, the Windows Task Manager still shows that 70-98% of the CPU is still being used. Before I hit the 'Start' button it is only 3-15% and after I close the program it returns to those values. But what is still happening when the SwingWorker already reported being done?? I'll give you a simplified version of my code: I have this StereoProcessor extending SwingWorker, with doInBackground(): yLoop for(some values y) { for(some values x) { if(isCancelled()) break yLoop; else { setProgress(to some value); // do some non-SingWorker-related stuff } } } return returnValue; I call to this process through another code: stereoProcessor.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if(evt.getPropertyName().equals("state")) if(evt.getNewValue().equals(StereoProcessor.StateValue.DONE) { // do stuff } } } }); stereoProcessor.computeSomething(); // this method calls execute() That's about it, so I don't understand what it keeps doing. I tried putting some System.outs in the code in different places, but all stopped printing after a while. Does anyone know what's going on? Edit: I noticed the CPU also keeps running after a simple call to a method in StereoProcessor that doesn't even call execute()...

    Read the article

  • Dynamic changes to thread stack size in Solaris 9 ?

    - by Satya
    Hello, I am looking for a configurable / tunable on Solaris 9 through which I can change the default thread stack size without recompiling the code to use "pthread_attr_setstacksize" For example on HPUX 11.11 / 11.23 the environment variable "PTHREAD_DEFAULT_STACK_SIZE" can be exported (available via HPUX patches PHCO_38307 / PHCO_38955 ) - Is there a equivalent Solaris 9 way to achieve the same ? Thanks! Satya

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >