SwingEvent thread and synchronization
I am having a problem where my app keeps locking up. I have a swing application that receives asynchronous realtime messages from a server.
On receiving these messages my views are required to update the components. I do this my calling a method with a synchronized block that updates the views components in a SwingUtilities.invokeLater clause.
This seems to work fine. However, sometimes when I click a menu item/button the app locks up.
I have put some debug in that shows me the synchronized block started but did not complete?!?!
I think this tells me that the SwingEvent thread interrupted my external notification thread, and caused some sort of deadlock.
If this is the case then why does my synchronized block of code not complete. I am not altogether sure what I should synchronize around.
For example I am doing something like this>
public void notify(Model model){
if(model == null) return;
synchronized(model){
System.out.println("started");
SwingUtilities.invokeLater(new Runnable(){
componentA.setText(model.getName());
System.out.println("ended");
My output when it locks is like this
started
ended
started
ended
started
At this point the app is frozen.
So I guess what I am asking is as follows>
Is the SwingEvent thread interrupting my external notification thread?
If so, why is the synchronized block not completing.
What should I synchronize?
Any help would be greatly appreciated.
Dr Nes
If there is a deadlock (which seems likley), and you are running on jdk 1.4.x, you simply have to do Ctrl-Break (on windows) or crtl-\ (on unix) to get the complete state of all threads and and lock objects. From this it should be fairly simple to figure out what is causing the problem.
Similar Messages
-
Help/advice needed SwinEvent thread and synchronization
I am having a problem where my app keeps locking up. I have a swing application that receives asynchronous realtime messages from a server.
On receiving these messages my views are required to update the components. I do this my calling a method with a synchronized block that updates the views components in a SwingUtilities.invokeLater clause.
This seems to work fine. However, sometimes when I click a menu item/button the app locks up.
I have put some debug in that shows me the synchronized block started but did not complete?!?!
I think this tells me that the SwingEvent thread interrupted my external notification thread, and caused some sort of deadlock.
If this is the case then why does my synchronized block of code not complete. I am not altogether sure what I should synchronize around.
For example I am doing something like this>
public void notify(Model model){
if(model == null) return;
synchronized(model){
System.out.println("started");
SwingUtilities.invokeLater(new Runnable(){
componentA.setText(model.getName());
System.out.println("ended");
My output when it locks is like this
started
ended
started
ended
started
At this point the app is frozen.
So I guess what I am asking is as follows>
Is the SwingEvent thread interrupting my external notification thread?
If so, why is the synchronized block not completing.
What should I synchronize?
Any help would be greatly appreciated.
Dr Nes
I can only assume thatI am having a problem where my app keeps locking up. I have a swing application that receives asynchronous realtime messages from a server.
On receiving these messages my views are required to update the components. I do this my calling a method with a synchronized block that updates the views components in a SwingUtilities.invokeLater clause.
This seems to work fine. However, sometimes when I click a menu item/button the app locks up.
I have put some debug in that shows me the synchronized block started but did not complete?!?!
I think this tells me that the SwingEvent thread interrupted my external notification thread, and caused some sort of deadlock.
If this is the case then why does my synchronized block of code not complete. I am not altogether sure what I should synchronize around.
For example I am doing something like this>
public void notify(Model model){
if(model == null) return;
synchronized(model){
System.out.println("started");
SwingUtilities.invokeLater(new Runnable(){
componentA.setText(model.getName());
System.out.println("ended");
My output when it locks is like this
started
ended
started
ended
started
At this point the app is frozen.
So I guess what I am asking is as follows>
Is the SwingEvent thread interrupting my external notification thread?
If so, why is the synchronized block not completing.
What should I synchronize?
Any help would be greatly appreciated.
Dr Nes
I can only assume that -
Help! about the thread and synchronize
I have worked on this assignment two days but I just can't get the answer it required
the src code is given below. Have to modify those codez using the semaphore.java which included in the zip to get the output written in test.out.txt(also in the zip)
http://adri.justmine.org/243.zip
can anyone help me on this? the assignment is due tommorrow, and I am already mad......Sorry about that.
Here is the src codes
import java.util.*;
*************** Hamlet.java **************************
class Hamlet extends Thread
public Hamlet() {
public void run() {
System.out.println("HAMLET: Armed, say you?");
System.out.println("HAMLET: From top to toe?");
System.out.println("HAMLET: If it assume my noble father's person");
System.out.println(" I'll speak to it, though hell itself should gape");
System.out.println(" And bid me hold my peace.");
*****************Marcellus.java******************************
import java.util.*;
class Marcellus extends Thread
public Marcellus() {
public void run() {
System.out.println("MARCELLUS: Armed, my lord.");
System.out.println("MARCELLUS: My lord, from head to foot.");
****************Bernardo.java**********************
import java.util.*;
class Bernardo extends Thread
public Bernardo() {
public void run() {
System.out.println("BERNARDO: Armed, my lord.");
System.out.println("BERNARDO: My lord, from head to foot.");
***************Semaphore.java*****************************
public class Semaphore
public Semaphore(int v) {
value = v;
public synchronized void P() {
while (value <= 0) {
try {
wait();
catch (InterruptedException e) { }
value--;
public synchronized void V() {
++value;
notify();
private int value;
***************CurtainUp.java***************
import java.util.*;
import Hamlet;
import Bernardo;
import Marcellus;
public class CurtainUp
public CurtainUp(int hprior, int bprior, int mprior) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
// Create the actor threads
Hamlet hamletThread = new Hamlet();
Bernardo bernardoThread = new Bernardo();
Marcellus marcellusThread = new Marcellus();
// Now set the priorities of the actor threads
hamletThread.setPriority(hprior);
bernardoThread.setPriority(bprior);
marcellusThread.setPriority(mprior);
hamletThread.start();
bernardoThread.start();
marcellusThread.start();
public static void main(String args[]) {
// Check to make sure that three arguments are passed in for thread
// priorities, and make sure that the numbers are within the right range.
// If they are, create an instance of CurtainUp.
if (args.length == 3) {
int hprior = Integer.parseInt(args[0]);
int bprior = Integer.parseInt(args[1]);
int mprior = Integer.parseInt(args[2]);
if ((hprior >= Thread.MIN_PRIORITY && hprior <= Thread.MAX_PRIORITY) &&
(bprior >= Thread.MIN_PRIORITY && bprior <= Thread.MAX_PRIORITY) &&
(mprior >= Thread.MIN_PRIORITY && mprior <= Thread.MAX_PRIORITY)) {
CurtainUp curtainUp = new CurtainUp(hprior, bprior, mprior);
else {
System.err.println("Range of priorities 1-10 inclusive");
else {
System.err.println("useage: Curtainup <priority1> <priority2> <priority3>");
********************tThe output *************************
java CurtainUp N1 N2 N3where N1, N2, N3 are numbers between 1 and 10 inclusive.
In your program output:
1. The order in which Bernardo and Marcellus deliver a shared line
should depend on which actor has higher priority. E.g.
java CurtainUp 1 1 2HAMLET: Armed, say you?
MARCELLUS: Armed, my lord.
BERNARDO: Armed, my lord.
HAMLET: From top to toe?
MARCELLUS: My lord, from head to foot.
BERNARDO: My lord, from head to foot.
HAMLET: If it assume my noble father's person
I'll speak to it, though hell itself should gape
And bid me hold my peace.
java CurtainUp 1 2 1HAMLET: Armed, say you?
BERNARDO: Armed, my lord.
MARCELLUS: Armed, my lord.
HAMLET: From top to toe?
BERNARDO: My lord, from head to foot.
MARCELLUS: My lord, from head to foot.
HAMLET: If it assume my noble father's person
I'll speak to it, though hell itself should gape
And bid me hold my peace.
2. If Bernardo and Marcellus have equal priority, it doesn't matter
which one goes first. E.g.
java CurtainUp 9 1 1HAMLET: Armed, say you?
MARCELLUS: Armed, my lord.
BERNARDO: Armed, my lord.
HAMLET: From top to toe?
BERNARDO: My lord, from head to foot.
MARCELLUS: My lord, from head to foot.
HAMLET: If it assume my noble father's person
I'll speak to it, though hell itself should gape
And bid me hold my peace.
3. Changing the priority of Hamlet in relation to the priorities of
Bernardo and Marcellus doesn't make any difference to the order in
which Hamlet speaks his lines. E.g.
java CurtainUp 9 2 1HAMLET: Armed, say you?
BERNARDO: Armed, my lord.
MARCELLUS: Armed, my lord.
HAMLET: From top to toe?
BERNARDO: My lord, from head to foot.
MARCELLUS: My lord, from head to foot.
HAMLET: If it assume my noble father's person
I'll speak to it, though hell itself should gape
And bid me hold my peace.
java CurtainUp 9 1 2HAMLET: Armed, say you?
MARCELLUS: Armed, my lord.
BERNARDO: Armed, my lord.
HAMLET: From top to toe?
MARCELLUS: My lord, from head to foot.
BERNARDO: My lord, from head to foot.
HAMLET: If it assume my noble father's person
I'll speak to it, though hell itself should gape
And bid me hold my peace. -
Kill a thread and remove the element from the vector
Hi All
I have attached each Vector element to a thread which I later want to kill and remove that element from the Vector.
Thread.join(milliseconds) allows this functionality to let the thread die after n milliseconds.
However, I want to delete this element from the Vector now.
Can someone please throw some light on this?
Here the code I have written for this:
try
System.out.println(counter);
int xCoord = generator.irand(25,200); // X-coord of AP
int yCoord = generator.irand(25,200); // Y coord of AP
listMN.addElement(new MobileNode((int)mnId,new Point2D.Double(xCoord,yCoord)));
listMNcoords.addElement(new Point2D.Double(xCoord,yCoord));
for(int i=0;i<vnuBS.returnBSList().size();i++)
if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=3)&&(vnuBS.returnBSList().get(i).getChannelCounter()>0))
double c = exponential() * 10000;
long timeToService = (long)c;
System.out.println("BS "+vnuBS.returnBSList().get(i).id+" is connected to MN ");
vnuBS.returnBSList().get(i).reduceChannelCounter();
System.out.println("Channel Counter Value Now: "+vnuBS.returnBSList().get(i).getChannelCounter());
mobileNodesThread.addElement(new Thread(listMN.elementAt(mobileNodeCounter)));
mobileNodesThread.elementAt(mobileNodeCounter).setName(mobileNodeCounter+"");
mobileNodesThread.elementAt(mobileNodeCounter).start();
mobileNodesThread.elementAt(mobileNodeCounter).join(100);
// System.out.println("Died");// thread dies after join(t) milliseconds.
System.out.println("ListMN getting generated : " + mobileNodesThread.get(mobileNodeCounter));
else if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=0))
listMN.remove(this.listMN.lastElement()); //dropcall
System.out.println("Removed "+mnId);
removeCounter++;
mnId = mnId--;
mobileNodeCounter--;
mnId = mnId+1;
Thanks a lot.I'm not sure if what you are trying to accomplish is correctly implemented.
The method join does not kill the thread. It will wait for the specified time for the thread to exit. If you want the thread to run for a specified ammount of time, develop the run method of that thread with that in mind. Do not try to kill it from the outside, but let it terminate itself (gracefull termination).
Now for your question regarding the vector (you should probably be using ArrayList nowadays): I would implement the observer pattern for this job. Make the threads post an event on the interface when they are done, let the main thread register itself with the threads and synchronize the method that handles the events. In that method you can remove the object from your list.
I'm not sure if you want to use thread anyhow, could you tell us what it is that you are trying to accomplish? -
Hi everyone,
I have a question about threads. I have a JDesktopPane in a Frame. I have added a number of JInternalFrame to the JDeskTopPane that is show/hide as required. This all works fine.
One particular internal frame is a frame that allows the training of a neural network. This process can take a long time so I am associated the neural network class with it's own thread and then calling "start()" (which runs the training sequence over the example set).
During the traning sequence events are fired and are picked up by NeuralNetwork listeners. This is so that the progress of the neural network training can be monitorred. For example, my internal frame has a progress bar that increments every time a training cycle is completed (a training sequence consists on many training cycles).
The problem occurs when the training sequence finishes. Somehoe things go haywire and my machine grinds to a halt. Everything slows down to a crawl and it is very difficult to get the machine to respond to anything.
I believe that it is something to do with the way that I have defined by events. I have an event class defined as follows;
/* CODE START */
public class NeuralNetworkEvent extends java.util.EventObject {
private int cycle = 0;
public int getCycle() { return this.cycle; }
public NeuralNetworkEvent(Object source, int cycle) {
super(source);
this.cycle = cycle;
/* CODE END */
And a listener defined like this;
/* CODE START */
public interface NeuralNetworkListener extends java.util.EventListener {
public void trainingCycleCompleted(NeuralNetworkEvent evt);
/* CODE END */
Events are fired to registered listeners from within the neural network class like this;
/* CODE START */
public void addNeuralNetworkListener(NeuralNetworkListener listener) { neuralNetworkListeners.add(listener); }
public void fireNeuralNetworkEvent() {
for (int count = 0; count < neuralNetworkListeners.size(); count++)
((NeuralNetworkListener)neuralNetworkListeners.get(count)).trainingCycleCompleted(new NeuralNetworkEvent(this, currentCycle));
/* CODE END */
And my internal frame (which is a NeuralNetworkListener) does this when a neural network event is fired;
/* CODE START */
pbNetwork.setValue(pbNetwork.getValue() + 1);
if ( evt.getCycle() == TOTAL_CYCLES - 1 ) cmdPredict.setEnabled(true);
/* CODE END */
Interestingly, execution never gets to the point where the predict button would be enabled (and I have checked the "if" statement for validity - it should resolve to "true"). In any case, is it at the point where the progress bar reaches 100% that everything goes haywire.
I hope that someone can help me this this - I am a little stuck with this.
Thanks in advance for you help. :)
BenHi,
Swing classes are not thread-safe. So if you want to update some Swing object (like the ProgressBar) from other than the Event Thread, use SwingUtilities.invokeLater(Runnable) or SwingUtilities.invokeAndWait(Runnable). Note, that firing an event takes place in the same Thread. So you might need to synchronize them as well. -
Trying to understand threads; interesting synchronize question
Ladies and Gentlemen,
what would happen if:
class c {
public synchronized void a() {
//do some stuff
b();
public synchronized void b() {
// do some stuff
this should cause a deadlock situation, should it not? The compiler doesnt complain when I try this.
Can someone confirm if this is correct:
any class method can be synchronized; it doesnt have to be a method in a thread you ahve created. Presumable, this method and its object are being manipulated by threads, so synchronization of data is necessary. I have a program that has multiple threads. Each thread get a reference to manager object (there is one object for all the threads, not one for each). Each thread has its own instance of an analysis object. The analysis object takes teh reference to the manager object in its constructor, so the end result is mulitple threads each have their own analysis object, and all of these objects point to one manager object. I want the methods of the manager object to be synchronized to avoid read/write conflicts and inconsistencies.
Thank you in advanceYou are right it is not officially deadlock. but it
is a situation that will produce an error if one is
not careful. b is called in a, and they both require
a lock, so the processing in b cant be done while a is
running. No, I'm telling you that is not the case. You can call b() from a() because if a thread is in a() it already has the lock needed to call b(). There is no possiblity of deadlock with the code you have written.
In order for a deadlock to be possible, you'd need to do something like this:
class Example
final lockObjectA = new Object();
final lockObjectB = new Object();
void a()
synchronized(lockObjectA)
b();
void b()
synchronized(lockObjectB)
a();
} -
Question about using threads and synchronizing objects
Hi all,
I am not that familiar and I have 2 questions.
QUESTION 1
I have a server which just sits and accepts incomming connections, then I spawn off a new thread which implements Runnable, and then call the run method. But the loop would not iterate, it would just sit inside the run method (which has rather long loop in it). I changed the class to extend Thread and called the start() method, rather than run(), and everything worked out fine.
Anyone know why this is?
QUESTION 2
So I am building a client server chat application where a user can be in multiple chat rooms. I have this personObject which has output/input streams. In the personObject, I create writeObject/ readObject method, which simply does as it implies.
I figured that I should make these methods synchronized, to ensure things run smoothly. however, when I made a call to readObject, which sat there and waited, and then made a call to writeObject, I would not enter the writeObject method. I took out the synchronized on the writeObject, and everything worked out fine.
I was under the assumption that synchronizing a method only synchronized on that method, not on the whole class. How come then was I not able to enter the writeObject method?
The more I think about it, I don't think I need to have these methods synchronized, but I thought it wouldn't hurt.
Thanks for the help.Hi all,
I am not that familiar and I have 2 questions.
QUESTION 1
I have a server which just sits and accepts incomming
connections, then I spawn off a new thread which
implements Runnable, and then call the run method.
But the loop would not iterate, it would just sit
inside the run method (which has rather long loop in
it). I changed the class to extend Thread and called
the start() method, rather than run(), and everything
worked out fine.
Anyone know why this is?
You should still implement Runnable, rather than extending Thread. Like this: Runnable r = new MyRunnable();
Thread t = new Thread(r);
t.start(); run() is just another method. Nothing special about it as far as multithreading or anything else goes.
start() is the method that actually spawns a new thread of execution.
I was under the assumption that synchronizing a
method only synchronized on that method, not on the
whole class. How come then was I not able to enter
the writeObject method?When you synchronize, you obtain a lock. As long as you hold that lock--until you exit the sync block or call wait()--no other thread can enter that block or any other block that obtains the same lock.
Two synchronized methods on the same object rely on obtaining the same lock--there's one lock for each object. -
The question about portlet customization and synchronization
I have a question about portlet customization and synchronization.
When I call
NameValuePersonalizationObject data = (NameValuePersonalizationObject) PortletRendererUtil.getEditData(portletRenderRequest);
portletRenderRequest.setPortletTitle(str);
portletRenderRequest.putString(aKey, aValue);
PortletRendererUtil.submitEditData(portletRenderRequest, data);
Should I make any synchronization myself (use "synchronized" blocks or something else) or this procedure is made thread-safe on the level of the Portal API?HI Dimitry,
I dont think you have to synchronize the block. i guess the code is synchronized internally.
regards,
Harsha -
Introduction of flow control and synchronization steps in Test Description
Hi ALL,
I am working on developing of Test Scripts in ATML standards. Can any one inform me how to introduce flow control (if, else, end, for, while, break etc) and synchronization (wait etc) steps into the Test scripts. Thanks in advance.
With Best Regards,
KalyanI had a similar issue in a project I am working on. I'm not sure if I did this the "Best Practices" way or not, but it works perfectly.
In the head area of my JSP I include the following:
<f:view>
<h:outputText id="refresher1" rendered="#{queryHandler.queryRunning}">
<f:verbatim escape="false">
<meta http-equiv="refresh"
content="5,<%=response.encodeURL(request.getContextPath()+
"/queryStatus.jsf")%>">
</f:verbatim>
</h:outputText>
<h:outputText id="refresher1" rendered="#{queryHandler.queryFinishedRunning}">
<f:verbatim escape="false">
<meta http-equiv="refresh"
content="5,<%=response.encodeURL(request.getContextPath()+
"/queryResults.jsf")%>">
</f:verbatim>
</h:outputText>This puts a 5 second refresh meta in the header to direct the browser to the correct page based on the status of the query thread.
There are many ways to accomplish the effect you want. I suggest putting all the controls into the JSP and making use of the rendered attributes instead of the JSTL conditionals to show the controls you want for the state of the application.
-jeffhoward -
Hello,
Does anyone know, how to overly and synchronize 2 or more videos of athletes, for example alpine skiers, using Premiere Pro? You can see that on the TV sometimes, where 2 racers are put into one track over each other and you can compare their rides? They are using special technology on the TV, probably Dartfish. But I hope somebody has some idea how to do it in Premiere? I have put one video over the second and set the opacity to 50%. Then I moved the upper video and adjusted its size, so that the gates (the skiers were at) matched. I created keyframes for couple of gates and for each of them I repeated the same and hoped Premiere would do the rest. But the result isn't good, the skiers drive away just a moment after leaving the gate. Any tips? Thanks. IvanJust for future reference, should anyone be looking at this thread for more information:
This link has a table with all major DIAdem features and what type of license (Base, Advanced or Professional) is required to use these features:
http://www.ni.com/diadem/buy/
The Professional license adds
3D model data mapping
GPS map layouts
to the features already present in the Advanced version (including video synchronization).
This page has a very detailed list of features, with more in depth descriptions and screen shots:
http://sine.ni.com/ds/app/doc/p/lang/en/id/ds-263#view.base
Maybe this is helpful to someone ...
Otmar
Otmar D. Foehner
Business Development Manager
DIAdem and Test Data Management
National Instruments
Austin, TX - USA
"For an optimist the glass is half full, for a pessimist it's half empty, and for an engineer is twice bigger than necessary." -
A problem with Threads and MMapi
I am tring to execute a class based on Game canvas.
The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
The MIDI tone "Stammers".
How to over come the problem?
Thanks in advance
Kobi
See Code example below:
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
public class MainScreenCanvas extends GameCanvas implements Runnable {
private MainMIDlet parent;
private boolean mTrucking = false;
Image imgBackgound = null;
int imgBackgoundX = 0, imgBackgoundY = 0;
Player player;
public MainScreenCanvas(MainMIDlet parent)
super(true);
this.parent = parent;
try
imgBackgound = Image.createImage("/images/area03_bkg0.png");
imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
catch(Exception e)
System.out.println(e.getMessage());
* starts thread
public void start()
mTrucking = true;
Thread t = new Thread(this);
t.start();
* stops thread
public void stop()
mTrucking = false;
public void play()
try
InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
player = Manager.createPlayer(is, "audio/midi");
player.setLoopCount(-1);
player.prefetch();
player.start();
catch(Exception e)
System.out.println(e.getMessage());
public void run()
Graphics g = getGraphics();
play();
while (true)
tick();
input();
render(g);
* responsible for object movements
private void tick()
* response to key input
private void input()
int keyStates = getKeyStates();
if ((keyStates & LEFT_PRESSED) != 0)
imgBackgoundX++;
if (imgBackgoundX > 0)
imgBackgoundX = 0;
if ((keyStates & RIGHT_PRESSED) != 0)
imgBackgoundX--;
if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
* Responsible for the drawing
* @param g
private void render(Graphics g)
g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
this.flushGraphics();
}You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
Regds,
SD
N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM -
Problem with threads and ProgressMonitor
Dear Friends:
I have a little problem with a thread and a ProgressMonitor. I have a long time process that runs in a thread (the thread is in an separate class). The thread has a ProgressMonitor that works fine and shows the tasks progress.
But I need deactivate the main class(the main class is the user interface) until the thread ends.
I use something like this:
LongTask myTask=new LongTask();
myTask.start();
myTask.join();
Now, the main class waits for the task to end, but the progress monitor don`t works fine: it shows only the dialog but not the progress bar.
What's wrong?Is the dialog a modal dialog? This can block other UI updates.
In general, you should make sure that it isn't modal, and that your workThread has a fairly low priority so that the UI can do its updating -
Having a problem with threads and using locks
I was hoping someone could give me some hits on getting my code to run properly. The problem I am having is I think my locks and unlocks are not working properly. Plus, for some reason I always get the same output, which is:
Withdrawal Threads Deposit Threads Balance
Thread 2 attempts $29 Withdrawal - Blocked - Insufficient Funds
Thread 4 attempts $45 Withdrawal - Blocked - Insufficient Funds
Thread 6 attempts $34 Withdrawal - Blocked - Insufficient Funds
Thread 7 attempts $40 Withdrawal - Blocked - Insufficient Funds
Thread 1 deposits $187 $187
Thread 3 deposits $169 $356
Thread 5 deposits $61 $417
Press any key to continue...If someone can see the error I made and doesn't mind explaining it to me, so I can learn from it, I would appreciate that very much.
/************Assign2_Main.java************/
import java.util.concurrent.*;
public class Assign2_Main
{//start Assign2_Main
public static void main(String[] args)
{//start main
// create ExecutorService to manage threads
ExecutorService threadExecutor = Executors.newCachedThreadPool();
Account account = new SynchronizedThreads();
Deposit deposit1 = new Deposit(account, "Thread 1");
Deposit deposit2 = new Deposit(account, "Thread 3");
Deposit deposit3 = new Deposit(account, "Thread 5");
Withdrawal withdrawal1 = new Withdrawal(account, "Thread 2");
Withdrawal withdrawal2 = new Withdrawal(account, "Thread 4");
Withdrawal withdrawal3 = new Withdrawal(account, "Thread 6");
Withdrawal withdrawal4 = new Withdrawal(account, "Thread 7");
System.out.println("Withdrawal Threads\t\tDeposit Threads\t\t\tBalance");
System.out.println("------------------\t\t---------------\t\t\t-------\n");
try
threadExecutor.execute(withdrawal1);
threadExecutor.execute(deposit1);
threadExecutor.execute(withdrawal2);
threadExecutor.execute(deposit2);
threadExecutor.execute(withdrawal3);
threadExecutor.execute(deposit3);
threadExecutor.execute(withdrawal4);
catch ( Exception e )
e.printStackTrace();
//shutdown worker threads
threadExecutor.shutdown();
}//end main
}//end Assign2_Main/******************Withdrawal.java****************************/
public class Withdrawal implements Runnable
{//start class Withdrawal
*constructor
public Withdrawal(Account money, String n)
account = money;
name = n;
public void run()
{//start ruin
int newNum = 0;
newNum = account.getBalance(name);
Thread.yield();
}//end run
private Account account;
private String name;
}//end class Withdrawal/*******************Deposit.java***************/
import java.util.Random;
public class Deposit implements Runnable
{//start class Deposit
*constructor
public Deposit(Account money, String n)
account = money;
name = n;
public void run()
{//start run
try
Thread.sleep(100);
account.setBalance(random.nextInt(200), name);
}// end try
catch (InterruptedException e)
e.printStackTrace();
}//end run
private Account account;
private Random random = new Random();
private String name;
}//end class Deposit/********************Account.java*****************/
*Account interface specifies methods called by Producer and Consumer.
public interface Account
//place sum into Account
public void setBalance(int sum, String name);
//return value of Account
public int getBalance(String name);
} /**************SynchronizedThreads.java****************/
import java.util.concurrent.locks.*;
import java.util.Random;
public class SynchronizedThreads implements Account
{//start SynchronizedThreads
*place money into buffer
public void setBalance(int amount, String name)
{//start setBalance
// lock object
myLock.lock();
sum += amount;
System.out.println("\t\t\t\t" + name + " deposits $" + amount +"\t\t$"+ sum+"\n");
//threads are singnaled to wakeup
MakeWD.signalAll();
// unlock object
myLock.unlock();
}//end setBalance
*gets the balance from buffer
public int getBalance(String name)
{//start getBalance
int NewSum = random.nextInt(50);
//lock object
myLock.lock();
try
if(sum > NewSum)
//takes NewSum away from the account
sum -= NewSum;
System.out.println(name + " withdraws $" + NewSum +"\t\t\t\t\t\t$"+ sum+"\n");
else
System.out.println(name + " attempts $" + NewSum + " Withdrawal - Blocked - Insufficient Funds\n");
//not enough funds so thread waits
MakeWD.await();
//threads are singnaled to wakeup
MakeD.signalAll();
}//end try
catch (InterruptedException e)
e.printStackTrace();
finally
//unlock object
myLock.unlock();
return NewSum;
}//end getBalance
private Random random = new Random();
private Lock myLock = new ReentrantLock();
private Condition MakeD = myLock.newCondition();
private Condition MakeWD = myLock.newCondition();
private int sum = 0;
}//end SynchronizedThreadsYou can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
Regds,
SD
N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM -
Java threads and WinLogon processes taking CPU!
We are seeing a strange problem. We have a multi-threaded java application
that is deployed on a Microsoft Windows 2000 server (SP4) with Citrix
Metaframe XP (Feature release 2). When this application starts, we start to see
multiple WINLOGON.EXE processes (20 plus) each taking up 1-2% of CPU -
this raises the CPU usage on the server significantly, impacting performance.
We have tested with JDK 1.3, 1.4, and 1.5 and see the same issues. If we
run the java application in a single thread, we dont see the same issue.
Has any one seen this problem before? Any suggestion on how this can be resolved?
Thanks in advance!Thanks for your replies. This is a Citrix environment where there are 50 plus
users logged in and there are 50 plus instances of Winlogon.exe always
running. Most of the time the cpu usage of these processes is 0.
We tried a multi-threaded program that lists files in a directory every few
seconds. There are 40 plus servers in the farm that we are deploying this
application on. We are seeing this problem on only some of the servers.
If we run a single thread from main(), we dont see the issue. But if we spawn
10 threads doing the scans periodically, we notice that as soon as all the threads
start, the WinLogons appear to start to take up CPU. When we stop the java
program, the WinLogon processes drop in CPU usage.
Is it possible that Java and WinLogon share some dlls that could be triggering
the WinLogon processes off?
We have tried running the single thread and multi-threaded programs around
same time and the correlation with the winlogons is clearly visible. If we add
sleep() soon after we start a thread, the winlogons seem to kick in later. -
I'm sorry if this is a cross post to my StringBuffer problem. I have run a test that instantiates the object in question and the memory gets collected so I don't think it's that. My question is on how memory pertaining to Threads is handled.
In my application I have a Thread array that launches X number of Threads. Currently 5. When an object wants a job run, the static Thread pool looks at the current thread and sees if it is still working. If it is, we sleep until it is available. Then I give it another job to do, start it, and move to the next thread.
Question 1 -
In a Thread [] is it better to replace the Thread at position x as in
threads[a] = new Thread();
threads[a].start();
or is it better to change some parameter in the thread and then call
start() again?
Question 2 -
I am currently using the second method. In my Thread object I have a MessageObject which contains a StringBuffer, which is eating memory. These MessageObject's are increasing. Some are being collected but many are staying live in the system and causing a memory error. When I do the following....
MyThread.MessageObject = new MessageObject()
That should make the original object available for cleanup right?
Should I call finalize on the MessageObject before replacing it?
Thanks you for any insights.If you want to use thread pools, and you can use JDK 5.0 (formerly known as J2SDK 1.5, codename Tiger), try using the java.util.concurrent package instead of writing your own thread pool (it's really difficult to make a thread pool right).
If you can't use JDK 5.0, you can try the original util.concurrent package ( http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html ) from Doug Lea. It's used in the JBoss Application Server, so it's tested and reliable.
If you need to use an object pool, try using the Commons Pool Component from Jakarta Apache: http://jakarta.apache.org/commons/pool/
Maybe you are looking for
-
Parental Controls do not control Front Row
Hello everyone- I have noticed that on my managed accounts if I do not select Front Row as a permitted application it runs just fine anyway from within the managed accounts. I can launch it from either the Finder or the keyboard shortcut and the cont
-
Hi all, Which table i have use to insert Stipend for the employee. And in case of student *** employee in the organisation, we have to insert 4 yrs stipend. suggest how to go ahead. Regards, Shahy
-
Rd client via rdweb cannot access local folder
hi, i recently installed remote-desktop web-service on Windows 2008 R2 for remote user to access a non-proprietary Microsoft application. the installation was made in one box include the application a. Remote Dekstop Session Host b. Remote Desktop Li
-
Error in tutorial: Could not create XML document carrying AQ Headers
Hi, We try to run the AQOutboundCorrelation tutorial. After running the enqueue_reply.sql script the message was placed from the request to the reply queue and read by the AQ inbound adapter. Nothing happened in the flow. The following error occured
-
How to Make a New Phone Number Entry in Address Book?
Can't for the life of me figure out how to do this via AppleScript. I want to create a new contact in Apple's Address Book, and populate the fields with some data. Here's what I have so far (keeping things simple): set theLastName to "Doe" set theFir