Client/Server in one program (using multiple threads)?
Is there some examples out there of how to use a client and server in a single program using separate threads? Also, is it possible to start a third thread to control the packets, such as drop a random or specified number of packets (or match on specific data in a packet)?
Just trying to have a client send udp packets to a server (all on the same machine running from the same program) and want to be able to drop packets coming from the client side to the server side.
E.g.,
Here's an example that I found here: http://compnet.epfl.ch/tps/tp5.html
import java.io.<strong>;
import java.net.</strong>;
import java.util.<strong>;
/</strong>
* Server to process ping requests over UDP.
public class PingServer {
private static double lossRate = 0.3;
private static int averageDelay = 100; // milliseconds
private static int port;
private static DatagramSocket socket;
public static void main(String[] args) {
// Get command line arguments.
try {
if (args.length == 0) {
throw new Exception("Mandatory parameter missing");
port = Integer.parseInt(args[0]);
if (args.length > 1) {
lossRate = Double.parseDouble(args[1]);
if (args.length > 2) {
averageDelay = Integer.parseInt(args[2]);
} catch (Exception e) {
System.out.println("UDP Ping Server");
System.out.println("Usage: java PingServer port [loss rate] [average delay in miliseconds]");
return;
// Create random number generator for use in simulating
// packet loss and network delay.
Random random = new Random();
// Create a datagram socket for receiving and sending UDP packets
// through the port specified on the command line.
try {
socket = new DatagramSocket(port);
System.out.println("UDP PingSever awaiting echo requests");
} catch (SocketException e) {
System.out.println("Failed to create a socket");
System.out.println(e);
return;
// Processing loop.
while (true) {
// Create a datagram packet to hold incoming UDP packet.
DatagramPacket request = new DatagramPacket(new byte[1024], 1024);
// Block until the host receives a UDP packet.
try {
socket.receive(request);
} catch (IOException e) {
System.out.println("Error receiving from socket");
System.out.println(e);
break;
// Print the received data.
printData(request);
// Decide whether to reply, or simulate packet loss.
if (random.nextDouble() < lossRate) {
System.out.println(" Reply not sent.");
continue;
// Simulate network delay.
try {
Thread.sleep((int) (random.nextDouble() * 2 * averageDelay));
} catch (InterruptedException e) {}; // Ignore early awakenings.
// Send reply.
InetAddress clientHost = request.getAddress();
int clientPort = request.getPort();
byte[] buf = request.getData();
DatagramPacket reply = new DatagramPacket(buf, buf.length,
clientHost, clientPort);
try {
socket.send(reply);
} catch (IOException e) {
System.out.println("Error sending to a socket");
System.out.println(e);
break;
System.out.println(" Reply sent.");
* Print ping data to the standard output stream.
private static void printData(DatagramPacket request) {
// Obtain references to the packet's array of bytes.
byte[] buf = request.getData();
// Wrap the bytes in a byte array input stream,
// so that you can read the data as a stream of bytes.
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
// Wrap the byte array output stream in an input stream reader,
// so you can read the data as a stream of characters.
InputStreamReader isr = new InputStreamReader(bais);
// Wrap the input stream reader in a buffered reader,
// so you can read the character data a line at a time.
// (A line is a sequence of chars terminated by any combination of \r
// and \n.)
BufferedReader br = new BufferedReader(isr);
// We will display the first line of the data.
String line = "";
try {
line = br.readLine();
} catch (IOException e) {
// Print host address and data received from it.
System.out.println("Received echo request from "
+ request.getAddress().getHostAddress() + ": " + line);
}I'm looking to do the "processing loop" in a separate thread, but I'd also like to do the client in a separate thread
So you're saying, just put the client code in a separate class and start the thread and that's it? As far as the packet rate loss thread, is this possible to do in another thread?
Similar Messages
-
Client-Server side GUI programming
I want to create a client-server side gui programming with java
i read this web adress
http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html
for information but there are some parts that i didnt understand and wait for your help
i m trying to build an online-help(live chat) system so when people press the start chat button a java page will appear but i wonder how this will connect to the person who is on server side
i mean is it possible to 2 users connect the same port and chat with each other
I mean when user press the chat button the online help supporter will be informed somebody wants to speak with him and they will start a chat
how can i do something like that
any help would be usefull thanksBelow is an example of a client/server program.
It shows how the server listens for multiple clients.
* TriviaServerMulti.java
* Created on May 12, 2005
package server;
* @author johnz
import java.io.*;
import java.net.*;
import java.util.Random;
* This TriviaServer can handle multiple clientSockets simultaneously
* This is accomplished by:
* - listening for incoming clientSocket request in endless loop
* - spawning a new TriviaServer for each incoming request
* Client connects to server with:
* telnet <ip_address> <port>
* <ip_address> = IP address of server
* <port> = port of server
* In this case the port is 4413 , but server can listen on any port
* If server runs on the same PC as client use IP_addess = localhost
* The server reads file
* Note: a production server needs to handle start, stop and status commands
public class TriviaServerMulti implements Runnable {
// Class variables
private static final int WAIT_FOR_CLIENT = 0;
private static final int WAIT_FOR_ANSWER = 1;
private static final int WAIT_FOR_CONFIRM = 2;
private static String[] questions;
private static String[] answers;
private static int numQuestions;
// Instance variables
private int num = 0;
private int state = WAIT_FOR_CLIENT;
private Random rand = new Random();
private Socket clientSocket = null;
public TriviaServerMulti(Socket clientSocket) {
//super("TriviaServer");
this.clientSocket = clientSocket;
public void run() {
// Ask trivia questions until client replies "N"
while (true) {
// Process questions and answers
try {
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader is = new BufferedReader(isr);
// PrintWriter os = new PrintWriter(new
// BufferedOutputStream(clientSocket.getOutputStream()), false);
PrintWriter os = new PrintWriter(clientSocket.getOutputStream());
String outLine;
// Output server request
outLine = processInput(null);
os.println(outLine);
os.flush();
// Process and output user input
while (true) {
String inLine = is.readLine();
if (inLine.length() > 0)
outLine = processInput(inLine);
else
outLine = processInput("");
os.println(outLine);
os.flush();
if (outLine.equals("Bye."))
break;
// Clean up
os.close();
is.close();
clientSocket.close();
return;
} catch (Exception e) {
System.err.println("Error: " + e);
e.printStackTrace();
private String processInput(String inStr) {
String outStr = null;
switch (state) {
case WAIT_FOR_CLIENT:
// Ask a question
outStr = questions[num];
state = WAIT_FOR_ANSWER;
break;
case WAIT_FOR_ANSWER:
// Check the answer
if (inStr.equalsIgnoreCase(answers[num]))
outStr="\015\012That's correct! Want another (y/n)?";
else
outStr="\015\012Wrong, the correct answer is "
+ answers[num] +". Want another (y/n)?";
state = WAIT_FOR_CONFIRM;
break;
case WAIT_FOR_CONFIRM:
// See if they want another question
if (!inStr.equalsIgnoreCase("N")) {
num = Math.abs(rand.nextInt()) % questions.length;
outStr = questions[num];
state = WAIT_FOR_ANSWER;
} else {
outStr = "Bye.";
state = WAIT_FOR_CLIENT;
break;
return outStr;
private static boolean loadData() {
try {
//File inFile = new File("qna.txt");
File inFile = new File("data/qna.txt");
FileInputStream inStream = new FileInputStream(inFile);
byte[] data = new byte[(int)inFile.length()];
// Read questions and answers into a byte array
if (inStream.read(data) <= 0) {
System.err.println("Error: couldn't read q&a.");
return false;
// See how many question/answer pairs there are
for (int i = 0; i < data.length; i++)
if (data[i] == (byte)'#')
numQuestions++;
numQuestions /= 2;
questions = new String[numQuestions];
answers = new String[numQuestions];
// Parse questions and answers into String arrays
int start = 0, index = 0;
String LineDelimiter = System.getProperty("line.separator");
int len = 1 + LineDelimiter.length(); // # + line delimiter
boolean isQuestion = true;
for (int i = 0; i < data.length; i++)
if (data[i] == (byte)'#') {
if (isQuestion) {
questions[index] = new String(data, start, i - start);
isQuestion = false;
} else {
answers[index] = new String(data, start, i - start);
isQuestion = true;
index++;
start = i + len;
} catch (FileNotFoundException e) {
System.err.println("Exception: couldn't find the Q&A file.");
return false;
} catch (IOException e) {
System.err.println("Exception: couldn't read the Q&A file.");
return false;
return true;
public static void main(String[] arguments) {
// Initialize the question and answer data
if (!loadData()) {
System.err.println("Error: couldn't initialize Q&A data.");
return;
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4413);
System.out.println("TriviaServer up and running ...");
} catch (IOException e) {
System.err.println("Error: couldn't create ServerSocket.");
System.exit(1);
Socket clientSocket = null;
// Endless loop: waiting for incoming client request
while (true) {
// Wait for a clientSocket
try {
clientSocket = serverSocket.accept(); // ServerSocket returns a client socket when client connects
} catch (IOException e) {
System.err.println("Error: couldn't connect to clientSocket.");
System.exit(1);
// Create a thread for each incoming request
TriviaServerMulti server = new TriviaServerMulti(clientSocket);
Thread thread = new Thread(server);
thread.start(); // Starts new thread. Thread invokes run() method of server.
}This is the text file:
Which one of the Smothers Brothers did Bill Cosby once punch out?
(a) Dick
(b) Tommy
(c) both#
b#
What's the nickname of Dallas Cowboys fullback Daryl Johnston?
(a) caribou
(b) moose
(c) elk#
b#
What is triskaidekaphobia?
(a) fear of tricycles
(b) fear of the number 13
(c) fear of kaleidoscopes#
b#
What southern state is most likely to have an earthquake?
(a) Florida
(b) Arkansas
(c) South Carolina#
c#
Which person at Sun Microsystems came up with the name Java in early 1995?
(a) James Gosling
(b) Kim Polese
(c) Alan Baratz#
b#
Which figure skater is the sister of Growing Pains star Joanna Kerns?
(a) Dorothy Hamill
(b) Katarina Witt
(c) Donna De Varona#
c#
When this Old Man plays four, what does he play knick-knack on?
(a) His shoe
(b) His door
(c) His knee#
b#
What National Hockey League team once played as the Winnipeg Jets?
(a) The Phoenix Coyotes
(b) The Florida Panthers
(c) The Colorado Avalanche#
a#
David Letterman uses the stage name "Earl Hofert" when he appears in movies. Who is Earl?
(a) A crew member on his show
(b) His grandfather
(c) A character on Green Acres#
b#
Who created Superman?
(a) Bob Kane
(b) Jerome Siegel and Joe Shuster
(c) Stan Lee and Jack Kirby#
b# -
Lots of info about one user using multiple computers. What about multiple users with separate Apple IDs using same computer? Having problems getting my wifes new iPhone talking to her apple account on the computer we share (2 users)
You need to create a user account for your wife (or yourself depending on who has the current user account). When syncing, each of you should sign in as a separate user, login to iTunes and then sync. I had this problem when my sister got an iPhone. When we did her initial sync, everything on my iPhone showed up on hers. Apple gave me this solution.
-
How do i use multiple threads( very much real time), using JavaFX?
I'm creating an application, using JavaFX because one can create awesome GUI using JavaFX. I need to know how to create real time multiple threads using javafx.
JavaFX doesn't support creation of multiple threads, but i think there is another way of doing it. I need it work in real time as my application works with an hardware (wacom intous 3 tablet), and i need mutiple threads to get all the parameters from the stylus of the tablet simultaneously...
any code which will help me out or explaination on how to go about this is appreciated...
Help required quickly...See example at
[http://jfxstudio.wordpress.com/2009/06/09/asynchronous-operations-in-javafx/|http://jfxstudio.wordpress.com/2009/06/09/asynchronous-operations-in-javafx/] -
How to use multiple threads and swing for displaying status/interaction
I have a Swing-app which have to show progress and allow userinteraction for these tasks:
* First:
retrieve a list of IDs(String) from the database (single thread running)
* Second:
some work on the id-list and list written to hd (same thread as above)
* Third:
retrieve Objects (based on the id-list) from different sources (Multiple Threads are running)
To show the status I have a JProgressBar (indeterminate while task1&2 running) and
a JTextArea showing the current status (connect,retrieve list, sort, ...)
When task3 is starting the JTextArea have to disappear and be replaced by a ScrollPane
with an array of Labels/TextAreas showing the status of each thread.
While theses threads are working, the ID-list will be consumed and the JProgressBar
shows the remaining precentage of the hole progress.
Everything is working so far (excepts UI :) , the problem(s) I have:
I need the threads to interacts with the user through the ui. e.g: "Connection to db-xyz lost! reconnect?"
But I don´t know how to do this correctly.
I think one way would be to send an event to the ui... but how?
(the ui must know which thread is calling to unpause it after user answered)
I know that threads should NOT change the swing(-container) - How do I notify the ui that a thread has a question?
Since these threads are really time-consuming the UI is not updated frequently,
how can I increase this? (perhaps using another thread-priority?)
thanks for help!if/when your threads need to interact with the UI, they can create a Runnable & send it to SwingUtilities.invokeLater or invokeAndWait. This Runnable can popup a message to the user, and act on the choice of the user (reconnect, cancel, ...). This action could be something which "unpauses" the task thread.
You may need to do synchronisation between the code in the Runnable & the Thread to which it is related - so the latter Thread knows when the user has made the choice. -
Is there any problem to use multiple threads to send email with JavaMail
Dear all,
I am using JavaMail 1.3.2 to send emails with SMTP, it works very well for a long time.
But one day, I found that the email service hanged and I could never send email again until I restart the tomcat. I found that the reason was a deadlock had been created, the required resource for sending email had not been released.
I guess the error is due to multiple threads are sending email at the same time. I made a test to create seperate thread for sending each email. After few days, I found this deadlock happened again. So, my question is: Can I use JavaMail with multiple threads? If not, I may need to sychronized all the thread that using JavaMail. I would like to make sure this is the reason for causing the deadlock problem.
Here is part of my code for using JavaMail:
transport = session.getTransport("smtp");
transport.connect(email_host, smtp_user, smtp_pass);
message.saveChanges();
transport.sendMessage(message,message.getAllRecipients());
which is very standard call, and it worked well for a long time.
Here is part for my thread dump on tomcat:
(Thread-339)
- waiting to lock <0x5447c180> (a sun.nio.cs.StandardCharsets)
(Thread-342)
- locked <0x5447c180> (a sun.nio.cs.StandardCharsets)
It seems that these happened after call the method transport.sendMessage() or message.updateChanges()
, and the underlying implementation may require the JRE StandardCharsets object. But the object had been locked and never be released. So, the sendMessage() or updateChanges() can't be completed.
Please give me some helps if you have any idea about it.
Thanks very much!
SiriusNote that the Nightly build gets updated daily (and sometimes more than once in case of a respin) and it is always possible that something goes wrong and it doesn't work properly, so be prepared for issues if you decide to stay with the Nightly build and make sure to have the current release with its own profile installed as well in case of problems.
See also:
* http://kb.mozillazine.org/Testing_pre-release_versions
*http://kb.mozillazine.org/Creating_a_new_Firefox_profile_on_Windows
*http://kb.mozillazine.org/Shortcut_to_a_specific_profile
*http://kb.mozillazine.org/Using_multiple_profiles_-_Firefox -
Client / Server Socket Communication - Should use 2 ports?
If we have a client server architecture using a socket based connection, should there be 2 serperate sockets? One dedicated to sending and one dedictated to receiving? What happens if both the client and server both send at the same time? How does that get handled? Does one of the messages get dropped? Thanks...
There are of course reasons you might want to use two sockets.
For instance security. One socket is encrypted and the other isn't. Or because the server initiates a confirmed port connection back it verifies the IP.
Or because the main socket is used for control and the second one is used for data. That way the client can tell the server to pause or make other adjustments in the data while the data is still flowing. -
Programs using multiple platforms
I have an online time tracking program that calls for JavaRE 1.3.x and an internal instant messaging client that calls for JavaRE 1.4.x
The time tracking program will run on MS VM but proves to have lock up issues. The instant messaging client can also run on the MS VM without issue. So, to eliminate all issues I need to have the time tracking program use JRE 1.3.x and the Instant messaging client use JRE 1.4.x or MS VM.
If I install the JRE 1.3.x and tell it to not be default, Instant messaging will work (through the MS VM) but the time tracking with have lock up issues as it will also use the MS VM. If I leave JRE 1.3.x checked as default, the time tracking software will work correctly but the instant messaging client will try to use JRE and redirects the user to the Java website to upgrade.
I hope this makes sense ... any suggestions?I agree with all of your statements. From what I understand, the tracking program upgrade is still about a year out and the instant message program is scheduled for rollout next month.
Thanks for the help ... I figured that this was the answer. -
Can one JVM use multiple X Windows displays?
I'm probably clutching at straws here, but is it possible for one JVM to use multiple X Windows displays? Consider this, I've got multiple video cards and each card has a different X session running on it (localhost:0 and localhost:1 for example). I start up a JVM that is displaying to :0 but I also want it to be able to display windows also on :1 without having to instantiate a new JVM.
Is this at all possible and any ideas on how it might be done?yes, this can be done. I think that you need to set the GraphicsDevice for the JFrames and JDialogs so that they appear in the right place. look at the class GraphicsEnvironment for more information.
-
Modifying the stack class to use multiple threads
Im trying to re write the stack class but with using 2 threads. One of the thread calls the pop method and the other calls the push method.
I don't know where im going wrong...
Any tips would be great thnx
Haven't bothered putting in any try / catch clauses yet, will make it look pretty later :)
http://nopaste.php-q.net/19555java.util.Stack is thread safe so all you need to do are create two threads
one which pushes data onto the stack and one which pops it off.
class PushThread implements Runnable {
private Stack stack;
public PushThread(Stack s) {
this.stack = s;
public void run() {
while(true) { // loop for ever
stack.push(new Object());
for(int i=0;i<100000;i++); // waste some time.
}The code above deliberatly does not use wait, sleep, notify etc as these
would force an ordering onto the stack. The code instead goes into a
loop that should waste time.
your PopThread class will be identical but will call stack.pop() instead.
matfud -
Using one object in multiple threads
Are there any drawbacks in using one instance of an object in several threads simultaneously, if this object has no instance variables?
I need to implement DAO in my project and I just wonder why DAOFactory every time creates a new DAO object, when DAO object doesn't have any instance variables?Are there any drawbacks in using one instance of an
object in several threads simultaneously, if this
object has no instance variables?
I need to implement DAO in my project and I just
wonder why DAOFactory every time creates a new DAO
object, when DAO object doesn't have any instance
variables?I don't think there are any problems with this. Since you have no instance variables there isn't really any overlap between the two threads. -
I'm pretty new to Java and am currently working on this assignment for one of my classes:
The goal is to create a program that will transfer an audio file using TCP/IP from a server to a client, then play the audio file. Additionally they wanted variable buffer sizes to measure the communication times when the buffer is changed. 've got all those parts complete (and good lord it took me days). The next step is to complete the same process, but begin playing the file before all the packets have been received by the client. That's where I'm stuck. Is a separate thread the way to go? If so, any suggestions on how to make that work would be appreciated.
Currently I'm dumping all the data into a ByteArray once it's been received, but I'm suspecting this won't work for real time streaming. Am I right in thinking this, and if that's the case, are PipedOutputStreams the solution? (And if they are, how do I pass values like that between threads?)
Below is the portion of code on the client side that works for transfer and play, but not for streaming.
Thanks in advance for any assistance.
<<<CODE>>>
//Setup data repository and transfer data to the array
byte[] byteData = new byte[byteCount];
int t=0;
double startTime = System.currentTimeMillis(); //Begin transfer time counter
while(t!=byteCount){
byteData[t]=inFromServer.readByte(); //Receive data
t++;
double endTime = System.currentTimeMillis() - startTime; //Calculate transfer time
System.out.println("Total Delay Time: " + endTime/1000 + " seconds");
//Stream the data into a byte array, set audio format, and setup the dataline
ByteArrayInputStream arrayStream = new ByteArrayInputStream(byteData,0,byteCount);
AudioInputStream audioStream = AudioSystem.getAudioInputStream(arrayStream);
AudioFormat audioFormat = audioStream.getFormat();
System.out.println("Now Playing: " + audioFormat);
DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class,audioFormat);
SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
//Transfer data to the audio source dataline and play
int counter;
while((counter = audioStream.read(byteData,0,byteData.length)) != -1){
if(counter >0)
sourceDataLine.write(byteData,0,counter);
sourceDataLine.drain();
sourceDataLine.close();Well nix that I managed to have a breakthrough and got things working. =)
Cheers! -
How to decrease CPU usage when using multiple threads?
I am using vb.net , .NetFramework 2.0 .
My application gets live stock prices from google and updates stocks in database each 10 seconds.
I get this code for multithreading. When application starts updating stocks in database(about 200 stocks) , the update takes up to 3 seconds but it increase CPU usage from 10 % to 70 % or 80 %.
What is the best way to to update database without getting CPU increase to high level?
I observed that all threads works at the same time. how to make each thread wait until the second ends?
This is my code. The problem is in function updateThreaded2().
Please I need quick help. Thanks
Public Function Update2(ByVal l As SortableBindingList(Of NewStockList)) As Long
res = 0
UThread = New System.Threading.Thread(AddressOf UpdateThreaded2)
If Me.URunning = True Then
Else
Try
Me.URunning = True
Interlocked.Exchange(Me.UCount, 0) 'threadsafe method of assigning static value
Interlocked.Exchange(Me.UDone, 0) 'threadsafe method of assigning static value
UThread.Priority = Threading.ThreadPriority.BelowNormal
UThread.IsBackground = True
UThread.Start(l)
Return 0
Catch ex As Exception
End Try
End If
End Function
Private Sub UpdateThreaded2(ByVal l As SortableBindingList(Of NewStockList))
Dim i As Integer = 0
Dim threadcount As Integer = Math.Min(Me.MaxThreads, Me.Stocks.Count)
Dim threads(threadcount - 1) As SUTC
Try
While i < Me.Stocks.Count
For j As Integer = 0 To threadcount - 1
If threads(j) Is Nothing Then
If i < Me.Stocks.Count Then
threads(j) = New SUTC(Me.Stocks(i), Me.DefaultService, AdjustSplits, Use20Minutes, l)
threads(j).Thread.Priority = Threading.ThreadPriority.BelowNormal
threads(j).Thread.IsBackground = True
threads(j).Thread.Start()
i += 1
End If
ElseIf threads(j).UpdateState = 0 Then
If i < Me.Stocks.Count Then
SecUpd(j) = Me.Stocks(i).symbol
threads(j) = New SUTC(Me.Stocks(i), Me.DefaultService, AdjustSplits, Use20Minutes, l)
threads(j).Thread.Priority = Threading.ThreadPriority.BelowNormal
threads(j).Thread.IsBackground = True
threads(j).Thread.Start()
i += 1
End If
End If
Next
Dim running As Boolean = True
While running
For j As Integer = 0 To threadcount - 1
If threads(j).UpdateState = 0 Then
Thread.Sleep(10)
running = False
SecUpd(j) = ""
Interlocked.Increment(UDone) 'threadsafe method of incrementing a variable by 1
Interlocked.Exchange(UCount, UCount + threads(j).UpdateCount) 'Threadsafe method for assigning a value
End If
Next
End While
End While
Dim pending As Integer = threadcount
Dim tempcount As Integer = 0
Dim oldcount As Integer = UCount
While pending > 0
pending = threadcount
tempcount = 0
For i = 0 To threadcount - 1
If threads(i).UpdateState = 0 Then
SecUpd(i) = ""
pending -= 1
tempcount += threads(i).UpdateCount
Thread.Sleep(10)
End If
Next
Interlocked.Exchange(UDone, Me.Stocks.Count - pending) 'Threadsafe method for assigning a value
Interlocked.Exchange(UCount, oldcount + tempcount) 'Threadsafe method for assigning a value
End While
Me.URunning = False
Catch ex As System.Threading.ThreadAbortException 'handle abort correctly
Dim pending As Integer = threadcount
Dim tempcount As Integer = 0
Dim oldcount As Integer = UCount
While pending > 0
pending = threadcount
tempcount = 0
For i = 0 To threadcount - 1
If threads(i).UpdateState = 0 Then
SecUpd(i) = ""
pending -= 1
tempcount += threads(i).UpdateCount
End If
Next
Interlocked.Exchange(UDone, Me.Stocks.Count - pending) 'Threadsafe method for assigning a value
Interlocked.Exchange(UCount, oldcount + tempcount) 'Threadsafe method for assigning a value
End While
End Try
End SubWhen the market is opened, stock prices changed every 500 ms . You can see this change on google finance.
I figured as much, but my thoughts are that if you can somehow find a way to make your program more event driven, then it may be possible to reduce unnecessary looping...
“If you want something you've never had, you need to do something you've never done.”
Don't forget to mark
helpful posts and answers
! Answer an interesting question? Write a
new article
about it! My Articles
*This post does not reflect the opinion of Microsoft, or its employees. -
When to acknowledge when dispatching using multiple threads?
So on a project I'm working on I read from a queue and I dispatch to a thread pool that has worker threads and the general idea is that I never want to acknowledge a message until I know for sure that I've processed it otherwise it risks becoming lost.
There are two approaches
1. is to acknowledge the message immediately after the details have been written to a working table and then in the event that the client restarts you pickup messages from this table prior to processing any new ones from the queue. upon processing each message you update it's state or delete the row from this table to reflect that it's no longer working.
2. another approach is to queue up acknowledgements in the main message listener thread such that as each worker thread completes it's job it enqueues the message for acknowledge by the main delivery thread (async). ie. the same thread that is picking up the messages. So after pulling a message from the queue and having dispatched it you then at the end of the cycle work thru the queue to acknowledge the messages that has been queued up by the worker threads to be acknowledged. One thing about this is that acknowleding a message implicitly acknowledges all those prior unacknowledged messages it's probably overkill to be acknowledging every message in the "queue." You just want to acknowledge the most recent one.
I believe that option 2 results in less work since there's no round trips to the database necessary to maintain a working table.
Websphere's MQ in JMS requires that you acknowledge in the delivery thread so unless you do it immediately or after processing each message you have to maintain a working table if you want to guarantee that any message pulled off the queue was actually processed and not lost along the way.steffi wrote:
So on a project I'm working on I read from a queue and I dispatch to a thread pool that has worker threads and the general idea is that I never want to acknowledge a message until I know for sure that I've processed it otherwise it risks becoming lost.
There are two approaches
1. is to acknowledge the message immediately after the details have been written to a working table and then in the event that the client restarts you pickup messages from this table prior to processing any new ones from the queue. upon processing each message you update it's state or delete the row from this table to reflect that it's no longer working.
2. another approach is to queue up acknowledgements in the main message listener thread such that as each worker thread completes it's job it enqueues the message for acknowledge by the main delivery thread (async). ie. the same thread that is picking up the messages. So after pulling a message from the queue and having dispatched it you then at the end of the cycle work thru the queue to acknowledge the messages that has been queued up by the worker threads to be acknowledged. One thing about this is that acknowleding a message implicitly acknowledges all those prior unacknowledged messages it's probably overkill to be acknowledging every message in the "queue." You just want to acknowledge the most recent one.
I believe that option 2 results in less work since there's no round trips to the database necessary to maintain a working table.certainly. but how exactly does it achieve your reliability goals from the first paragraph?
Websphere's MQ in JMS requires that you acknowledge in the delivery thread so unless you do it immediately or after processing each message you have to maintain a working table if you want to guarantee that any message pulled off the queue was actually processed and not lost along the way.sounds about right, yes. -
More than one programs using report generator at the same time
Hi,
I want to ask that how can I use Report Generator in two program at the same time.
As I am using Report Generator to log my data into excel, I find that if there are two
programs contain Report Generator, the program which ran first cannot find its
report.What can I do apart from alway open a new report?
RyanRyan,
Could you elaborate on what you mean when you say that the program which ran first cannot find its report? Are you trying to modify the same report simultaneously with these different apps?
Regards,
Jared Boothe
Staff Hardware Engineer
National Instruments
Maybe you are looking for
-
Need to be "released" from Veizon Blackberry Server to get BIS in New Zealand??
I have a Verizon Blackberry Tour that has been unlocked. I am now with Vodafone New New Zealand and have registered for Blackberry Internt Service with Vodafone. It does not currently work - Vodafone tells me that the phone is registered on Verizon
-
When I run the payment wizard I get an error from within SBO when it comes to display the Payment Methods. I have run profiler and the SQL that SBO generates is corrupt. Just wondering if anybody else has had this and knows of a fix? SELECT T0.PayMe
-
How do I change the number?
I bought a Iphone 4s from my friend with the sim card in it, and it still has his number in the phone. I have the serial number to it. The problem is that when I went to the sprint store, it said that the Iphone was either lost or stolen so I couldn'
-
Photo Sync with new iPhoto Library
I created a new iPhoto-Library. This one is now set as "standard". But if i try to sync the photos from this new library to the iPhone, iTunes still shows the pictures from the old iPhoto-Library. How can I tell iTunes to use the new library?
-
Dear members, I use Forms 6i c/s, with a 8.1.7 database. I have two blocks, with a master-detail relation between them. When I try to search for records in the detail block (Enter-Query / Execute-Query), I get only one record: the one that was synchr