While Loop - Object Creation

Hello,
I have a question on object creation and while loops. Have a look at the following code snippet:
while(true)
       Object obj = new Object();
       // Pass off obj to a new thread
       Thread job = new Thread(new ObjectHandler(obj));
       job.start();
}My question is, do I have to wait until the newly created Thread is finished with the Object obj before I can create a new Object called obj in the while loop?
Also does anyone have any documentation on this sort of thing?
Thanks,
Tony.

Jaxie wrote:
I'm still not sure you get what I'm on about, you might want to read up on java methods and pass by value.I think we know how it works. Most of us have been programming in Java for serveral years.
>
When you pass an object to a method in java you pass it a copy of a reference to that object. Leading on from that, before an object is eligible for garbage collection in java, all references to that object must be dropped.
So with all that in place, my question was, is the creation of an object in a while loop dependent on previous objects of the same name? Objects don't have names. Have we mentioned that before?
You have a reference, larry that is referencing an unnamed object. You can also create other references that reference the same object. The thread will have one reference. You can then make larry reference another object. That will not change anything in the thread. It will still reference the old object, and that object will not be claimed by the gc until that thread stops referencing it.
So the second time we go through the loop below, do we have to wait until larry has been garbage collected, before a new larry can be created?Read the articles/tutorials and what I have written above. What do you think?
Do also note that the GC isn't executed synchronously.

Similar Messages

  • Error while lock object creation

    Hi
    When I tried to create a lock object, I get the following error.
    Error: "Total length of lock argument for table XXXXXXXXX longer than 150"
    I have 3 tables in which Table1 is the check table for the value tables (Table2 & Table3). During the process of deletion of a record from Table1 (CT) I need the lock tobe established on value tables and then I delete all the corresponding entries in value tables are also deleted.
    Would like to know If there is any other std ways of doing this ? and
    Solution to overcome the error.
    Regards
    Karthick

    Hi,
    I think the error is becoz you have given too many LOCK parameters in the lock object. the total length of the PARAMTERS of lock object should not exceed 150.
    By default all the KEY fields will be taken as Lock paramters, so your table key's length is more than 150.
    Also why dont you create 3 lock objects for each table and then use only KEY's of each table as LOCK PARAMETERS.
    Then Lock T1 record first then lock T2 and T3 records, then delete records from T2 and T3.
    Then you delete T1 record.
    The execute DEQUEUE_ALL.
    Regards,
    Sesh

  • While loop using a timer object

    Hello Technet,
    I have a file that gets created every night by a batch job and I need to send that file every night. So, I came up with a method (if there's a better way, I'd like to hear). I created a 2 hour timer object to run a while loop. While the time elapsed is less
    than 2 hours, the loop will run.  In the loop, I have a if condition to test for a file.  If the file is not there, then sleep for 10 minutes.  If the file is there, then send it to me with send-mailmessage. The problem is, I will get the file
    sent to me at every interval because the loop is terminated by the timer. I would like the loop to terminate once the email message is sent to me.  Here is my code snip. Can someone please help on getting the loop to terminate when the message is sent?
    $file = "c:\file.txt"
    $timeout = new-timespan -hours 2
    $sw = [diagnostics.stopwatch]::StartNew()
    while ($sw.elapsed -lt $timeout)
    if(!(test-path -path "$file1"))
    file is not there...yet
    start-sleep -seconds 600
    else
    $SmtpServer = "relay"
    $To = "my@emailaddr"
    $From = "me@emailaddr"
    $Subj = "Got it"
    $Attm = "$file1"
    $Body = "Please see Attachment"
    Send-MailMessage -smtpserver $SmtpServer -from $From -to $To -subject $Subj -body $Body -attachment $Attm

    Hi,
    You can use break:
    http://ss64.com/ps/break.html
    EDIT: Alternatively, you can try this:
    $filePath = 'c:\file.txt'
    $found = $false
    Do {
    $file = Test-Path -Path $filePath
    If ($file) {
    Send-MailMessage -To [email protected] -From [email protected] -Subject 'Got it' -Body 'Please see Attachment' -Attachments $filePath -SmtpServer smtp.domain.com
    $found = $true
    Else {
    Start-Sleep -Seconds 600
    Until ($found -eq $true)
    This will loop until the file is found instead of relying on a timer.
    Don't retire TechNet! -
    (Don't give up yet - 12,700+ strong and growing)

  • What's wrong with this while loop?

    Hi, folks. for the code fragment blow, resultSetArray holds two objects of type ResultSet. From those println statement, i can see the whole while loop(the most outter one) process goes alrite the first time right from begining to the end. However, when variable j increases from 0 to 1, the code stops executing at the the line while(rs.next). I just couldnt figure out what causes the problem while i've been fighting with it for several hours. Could someone plz throw me some lights? With your help, i could possibly go to bed before sun rises...
            while(j<resultSetArray.length)
              //for(int j=0; j<resultSetArray.length; j++)
    System.out.println("show me j is called twice " + j);
                   ResultSet rs = resultSetArray[j];
    System.out.println("the converting rs object is called twice and it is not null " + rs);
                  int numWantedColumns = wantedColumnNames.size();
                  //if it's about go or single trip
                  if(j==0 && rs != null)
                      go = new Element("Go");
                       //go.setText("go");
                       //result.addContent(go);
                  //if it's about return trip
                  else if(j==1 && rs != null)
                      back = new Element("Back");
                       //back.setText("back");
                       //result.addContent(back);
                  if(rs!= null)
    System.out.println("this hell is called twice coz it's not null");
                   while(rs.next())
    System.out.println("what about here?");
                        Element flightInfo = new Element("FlightInfo");
         System.out.println("while rs.next() is called");
                        for (int i = 0; i < numWantedColumns; i++)
                           String columnName   = (String)wantedColumnNames.get(i);
         System.out.println("column name is " + columnName);
                           String value = rs.getString(columnName);
          System.out.println("column value is " + value);
                           flightInfo.addContent(new Element(columnName).setText(value));
                        if(j==0)
                           go.addContent(flightInfo);
                        else if(j==1)
                             back.addContent(flightInfo);
                   else if(rs == null)
                        break;
                   j++;
             }

    i've got the problem sort out, eventually. there was actually nothing wrong with the while loop. it was caused by a typo in databse, instead of having Brisbane, i typed Bisbane. The single letter r cost me more than 6 hours to figure it out. it was such a painful feeling while i realized i made a such stupid mistake.
    by the way, as jnw777 mentioned, output rs.next() info instead of the test line. i did try it, however i didnt realize even System.out.println(rs.next()) would cause the cursor move down one row from its current position. so, plus the original while(rs.next()) statement, it was moving the cursor two rows down at a time! And i just couldnt think of this caused me the fact i was only getting the even number row of the ResultSet while i was sniffing the bug from a class with 700+ lines of code. I was so excited and just couldnt stop yelling at the moment i got over it! That was a damn execiting moment...
    now, i am wondering if anyone in this wonderland would like to share his/her stories.

  • How can i get the while loop to enter a different loop beside the first one

    I can't seem to figure out how to change the value to enter into one of the other while statements in the script. I am new to this and can't seem to find anything how to enter in the information to be able to go to different while statements and then run
    what is located in that statement.
    The script is supposed to let me choose between TC, MonsterLock, and Cyc and then jump to the while statement that is associated with one of them and then run what ever is located in that block. All i am getting is a infinite loop and it never sees the other
    while loops. I have 3 set up the go along with the first statement but no matter what i type in for them it always looks at the first while statement and stays there.
    Can someone please help me with having it do what i stated earlier.  
    write-host "This script sets up DATABASE Staging"
    $ProductionDistro = Read-Host -Prompt "Which production do you `enter code here`want to run?(TC/MonsterLock/Cyc)"
    While($ProductionDistro -notmatch "(TC|MonsterLock|Cyc)"){
    write-host "You have entered an error" -ForegroundColor Red
    write-host "You must type TC or MonsterLock or Cyc"
    write-host "you typed $ProductionDistro"
    write-host "This script sets up DATABASE Staging"
    $ProductionDistro = Read-Host -Prompt "Which production do you `enter code here`want to run?(TC/MonsterLock/Cyc)"
    while($ProductionDistro -match $TC) {
    write-host "Sets up location you want to run staging"
    $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
    While($ElementDistro -notmatch "(DATABASE1|DATABASE2|DATABASE3|DATABASE4|ALL)") {
    write-host "you have enterd an error" -ForegroundColor Red
    write-host "You must type DATABASE1 or DATABASE2 or DATABASE3 or DATABASE4 or ALL"
    write-host "you typed $ElementDistro"
    write-host "set location you want to run staging"
    $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
    While($PrductionDistro -match $MonsterLock){
    write-host "Sets up location you want to run staging"
    $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
    While($ElementDistro -notmatch "(DATABASE1|DATABASE2|DATABASE3|DATABASE4|ALL)") {
    write-host "you have enterd an error" -ForegroundColor Red
    write-host "You must type DATABASE1 or DATABASE2 or DATABASE3 or DATABASE4 or ALL"
    write-host "you typed $ElementDistro"
    write-host "set location you want to run staging"
    $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
    while( $ElementDistro -match $DATABASE1 ){
    function Execute-MySqlcommand {param( [string]$Server, #the host of the SQL server
    [string]$Database1, #the name of the database
    [System.Data.MySqlclient.MySqlcommand]$Command) #the command to execute (name of stored command)
    $mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
    $MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE1.DATABASE1S2.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE1.DATABASE1S3.BTXSUPB"
    $MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE1.DATABASE1S2.BTXADDR;TRUNCATE TABLE DATABASE1.DATABASE1S3.BTXSUPB; INSERT INTO DATABASE1.DATABASE1S3.BTXSUPB SELECT * FROM DATABASE1.DATABASE1S2.BTXSUPB; select count(*) from DATABASE1.DATABASE.BTXADDR; select count(*) from DATABASE1S.DATABASE.BTXADDR; select count(*) from DATABASE1.DATABASE.BTXSURB; select count(*) from DATABASE1S.DATABASE.BTXSUPB;"
    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $mysqlConnection
    $mysqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $mysqlConnection.Close()
    if ($Result -gt 0) {return $True} else {return $False}
    function Execute-MySQLCommand {param( [string]$Server, #the host name of the SQL server
    [string]$DATABASE1, #the name of the database
    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE1;Description=DATABASE1;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE1;DATASET=DEFAULT"
    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $sqlConnection
    $sqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $sqlConnection.Close()
    if ($Result -gt 0) {return $TRUE} else {return $FALSE}
    function Copy-File {
    #.Synopsis
    # Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
    param}($DATABASE0980453.pkg,"d/DATABASE1/code_stg")
    # create destination if it's not there ...
    #mkdir $destination -force -erroraction SilentlyContinue
    foreach($original in ls $source -recurse) {
    $result = $original.FullName.Replace($source,$destination)
    while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }
    if($original.PSIsContainer) {
    # mkdir $result -ErrorAction SilentlyContinue
    # } else {
    copy $original.FullName -destination $result
    cd /d/DATABASE1/code_stg
    install ../DATABASE0980453.pkg
    while($ElementDistro -match $DATABASE2 ) {
    function execute-MySqlcommand {param( [string]$Server, #the host of the SQL server
    [string]$DataBase2, #the name of the database
    [System.Data.MySqlclient.MySqlcommand]$Command) #the command to execute (name of stored command)
    $mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
    $MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE2.DATABASE2MS2.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE2.DATABASE2S3.BTXSUPB"
    $MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE2.DATABASE2S2.BTXADDR;TRUNCATE TABLE DATABASE2.DATABASE2S3.BTXSUPB; INSERT INTO DATABASE2.DATABASE2S3.BTXSUPB SELECT * FROM DATABASE2.DATABASE2S2.BTXSUPB; select count(*) from DATABASE2.DATABASE.BTXADDR; select count(*) from DATABASE2S.DATABASE.BTXADDR; select count(*) from DATABASE2.DATABASE.BTXSURB; select count(*) from DATABASE2S.DATABASE.BTXSUPB;"
    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $mysqlConnection
    $mysqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $mysqlConnection.Close()
    if ($Result -gt 0) {return $True} else {return $False}
    function Execute-MySQLCommand {param( [string]$Server, #the host name of the SQL server
    [string]$DATABASE2, #the name of the database
    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE2; Description=DATABASE2; Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE2;"
    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $sqlConnection
    $sqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $sqlConnection.Close()
    if ($Result -gt 0) {return $TRUE} else {return $FALSE}
    function Copy-File {
    #.Synopsis
    # Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
    param}($DATABASE0980453.pkg,"d/DATABASE2/code_stg")
    # create destination if it's not there ...
    #mkdir $destination -force -erroraction SilentlyContinue
    foreach($original in ls $source -recurse) {
    $result = $original.FullName.Replace($source,$destination)
    while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }
    if($original.PSIsContainer) {
    # mkdir $result -ErrorAction SilentlyContinue
    # } else {
    copy $original.FullName -destination $result
    cd /d/DATABASE2/code_stg
    install ../DATABASE0980453.pkg
    While( $ElementDistro -match $DATABASE3 ) {
    function Execute-MySqlcommand {param( [string]$Server, #the host of the SQL server
    [string]$DATABASE3, #the name of the database
    [System.Data.MySqlclient.MySqlcommand]$Command) #the command to execute (name of stored command)
    $mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
    $MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE3.DATABASE3S2.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE3.DATABASE3S3.BTXSUPB"
    $MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE3.DATABASE3S2.BTXADDR;TRUNCATE TABLE DATABASE3.DATABASE3S3.BTXSUPB; INSERT INTO DATABASE3.DATABASE3S3.BTXSUPB SELECT * FROM DATABASE3.DATABASE3S2.BTXSUPB; select count(*) from DATABASE3.DATABASE.BTXADDR; select count(*) from DATABASE3S.DATABASE.BTXADDR; select count(*) from DATABASE3.DATABASE.BTXSURB; select count(*) from DATABASE3S.DATABASE.BTXSUPB;"
    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $mysqlConnection
    $mysqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $mysqlConnection.Close()
    if ($Result -gt 0) {return $True} else {return $False}
    function Execute-MySQLCommand {param( [string]$Server, #the host name of the SQL server
    [string]$DATABASE3, #the name of the database
    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE3;Description=DATABASE3;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE3;"
    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $sqlConnection
    $sqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $sqlConnection.Close()
    if ($Result -gt 0) {return $TRUE} else {return $FALSE}
    cd /d/DATABASE3/code_stg
    install ../DATABASE0980453.pkg
    function Copy-File {
    #.Synopsis
    # Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
    param}($DATABASE0980453.pkg,"d/DATABASE3/code_stg")
    # create destination if it's not there ...
    #mkdir $destination -force -erroraction SilentlyContinue
    foreach($original in ls $source -recurse) {
    $result = $original.FullName.Replace($source,$destination)
    while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }
    if($original.PSIsContainer) {
    # mkdir $result -ErrorAction SilentlyContinue
    # } else {
    copy $original.FullName -destination $result
    While($ElementDistro -match $DATABASE4 ) {
    function Execute-MySqlcommand {param( [string]$Server, #the host of the SQL server
    [string]$DATABASE4, #the name of the database
    [System.Data.MySqlclient.MySqlcommand]$Command) #the command to execute (name of stored command)
    $mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
    $MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE4.DATABASE42.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE4.DATABASE4S3.BTXSUPB"
    $MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE4.DATABASE4S2.BTXADDR;TRUNCATE TABLE DATABASE4.DATABASE4S3.BTXSUPB; INSERT INTO DATABASE4.DATABASE4S3.BTXSUPB SELECT * FROM DATABASE4.DATABASE4S2.BTXSUPB; select count(*) from DATABASE4.DATABASE.BTXADDR; select count(*) from DATABASE4S.DATABASE.BTXADDR; select count(*) from DATABASE4.DATABASE.BTXSURB; select count(*) from DATABASE4S.DATABASE.BTXSUPB;"
    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $mysqlConnection
    $mysqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $mysqlConnection.Close()
    if ($Result -gt 0) {return $True} else {return $False}
    function Execute-MySQLCommand {param( [string]$Server, #the host name of the SQL server
    [string]$DATABASE4, #the name of the database
    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE4;Description=DATABASE4;Trusted_Connection=Yes;WSID=Server;DATABASE=TF90PVS;"
    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $sqlConnection
    $sqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $sqlConnection.Close()
    if ($Result -gt 0) {return $TRUE} else {return $FALSE}
    function Copy-File {
    #.Synopsis
    # Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
    param}($DATABASE0980453.pkg,,"d/DATABASE4/code_stg")
    # create destination if it's not there ...
    #mkdir $destination -force -erroraction SilentlyContinue
    foreach($original in ls $source -recurse) {
    $result = $original.FullName.Replace($source,$destination)
    while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }
    if($original.PSIsContainer) {
    # mkdir $result -ErrorAction SilentlyContinue
    # } else {
    copy $original.FullName -destination $result
    cd /d/DATABASE4/code_st
    install ../DATABASE0980453.pkg
    While($ElementDistro -match $ALL ){
    function Execute-MySQLCommand {param( [string]$Server, #the host name of the SQL server
    [string]$DATABASE1,$DATABASE2,$DATABASE3,$DATABASE4, #the name of the database
    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $sqlConnection.ConnectionString = "(DATABASE_CONNECT_STRING=DSN=DATABASE1;Description=DATABASE1;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE1;DATASET=DEFAULT;),(DATABASE_CONNECT_STRING=DSN=DATABASE2; Description=DATABASE2; Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE2;),(DATABASE_CONNECT_STRING=DSN=DATABASE3;Description=DATABASE3;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE3;),(DATABASE_CONNECT_STRING=DSN=DATABASE4;Description=DATABASE4;Trusted_Connection=Yes;WSID=Server;DATABASE=TF90PVS;)"
    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $sqlConnection
    $sqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $sqlConnection.Close()
    if ($Result -gt 0) {return $TRUE} else {return $FALSE}
    install ../DATABASE0980453.pkg
    While($ProductionDistro -match $Cyc) {
    write-host "Sets up location you want to run staging"
    $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
    While($ElementDistro -notmatch "(DATABASE1|DATABASE2|DATABASE3|DATABASE4|ALL)") {
    write-host "you have enterd an error" -ForgroundColor Red
    write-host "You must type DATABASE1 or DATABASE2 or DATABASE3 or DATABASE4 or ALL"
    write-host "you typed $ElementDistro"
    write-host "set location you want to run staging"
    $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"

    OK, so you've got a reasonable input loop early on:
    write-host "This script sets up DATABASE Staging"
    $ProductionDistro = Read-Host -Prompt "Which production do you `enter code here`want to run?(TC/MonsterLock/Cyc)"
    While($ProductionDistro -notmatch "^(TC|MonsterLock|Cyc)$"){
    write-host "You have entered an error" -ForegroundColor Red
    write-host "You must type TC or MonsterLock or Cyc"
    write-host "you typed $ProductionDistro"
    write-host "This script sets up DATABASE Staging"
    $ProductionDistro = Read-Host -Prompt "Which production do you `enter code here`want to run?(TC/MonsterLock/Cyc)"
    I've only added two things to that code:  a ^ and $ at the beginning and end of your regex pattern.  As originally written, it would have successfully matched any string containing TC, MonsterLock or Cyc (such as "bogusTCwhatever", etc).
    Now, instead of a bunch of extra While loops based on $ProductionDistro, what you need is some conditionals (either a Switch statement, or some If/ElseIf).  For example:
    switch ($ProductionDistro)
    'TC'
    # Do TC Stuff
    break
    'MonsterLock'
    # Do MonsterLock Stuff
    break
    'Cyc'
    # Do Cyc stuff
    break

  • Can't break out of a while loop

    Hi, I am doing a networking course, for which an assignment was to write an echo client and server. I did the assignment in Java and it works just fine. However, there is something I don't understand that is bugging me. I wanted a way to stop the server by either detecting when the client entered "quit" or when the user of the server entered "quit". This was not part of the assignment, but after trying many different things I really want to know (1) what I am doing wrong and (2) what the correct way to do things would be.
    I tried to put an "if" clause within the while loop so that if the client entered "quit" the server would detect that, close the socket connections, and break the while loop. But... it seems that I have done this wrong and I am not sure why.
    (Note - I am not a Java programer - just a beginner, and the course in question isn't a programming course. I did the program below by following some brief guidelines/tutorial. I don't even have any books on Java to consult right now - just ordered few from Amazon for any future projects.)
    The code:
    // EchoServer.java     - a simple server program. It listens on a predetermined port for an incoming connection.
    //                After a client connects they can input a line of text and
    //                the server will echo the exact same line back.
    import java.io.*;
    import java.net.*;
    public class EchoServer {
         protected static int DEFAULT_PORT = 3004;
         public static void main (String args[]) throws Exception {
              int portNumber;          
              try {
                   portNumber = Integer.parseInt(args[0]);
              } catch (Exception e) {
                   portNumber = DEFAULT_PORT;
              ServerSocket myServer = null;
                try{
                   myServer = new ServerSocket(portNumber);      
                   System.out.println("Echo Server started. Listening on port " + portNumber);
              } catch (IOException e) {
                   System.out.println("Could not listen on port: " + portNumber);
                   System.out.println(e);
              Socket clientSocket = null;                         
              try{          
                     clientSocket = myServer.accept();
              } catch (IOException e) {
                     System.out.println("Accept failed:  " + portNumber);
                   System.out.println(e);
              BufferedReader input = null;     
              PrintWriter output = null;
              try {               
                   input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                   output = new PrintWriter(clientSocket.getOutputStream(), true);
              } catch (IOException e) {
                   System.out.println(e);
              String theLine;     
              while(true){
                   theLine = input.readLine();
                   output.println(theLine);     
                   output.flush();
                        if (theLine.equals("quit"))  {
                             input.close();
                             output.close();
                             clientSocket.close();
                             myServer.close();     
                             break;
                        }     // end if
              }     // end while     
         }     // end main
    }          // end EchoClient

    A few observations:
    - You might as well exit after you have caught your exceptions, since none of the conditions I see would allow your program to run properly afterwards. You can either do that by a System.exit(int) or a return;
    - Although this s an example program, you should take advantage of doing things right. Addining a try-finally would be good for tidying things up. First declare your variables before the main try, otherwise the finally won't be able to do its job. For example (this won't compile as is):
    Socket clientSocket = null;
    ServerSocket myServer = null;
    InputStream in = null;
    OutputStream out =null;
    try {
      String theLine = null;     
      while( (theLine = input.readLine()) != null ){
        output.println(theLine);     
        output.flush();
        if (theLine.equals("quit"))  {
           break;
      }     // end while
    } catch ( IOException ex ) {
      ex.printStackTrace();
    } finally {
      if ( in != null ) {
         in.close();
      if ( out != null ) {
         out.close();
      // add other conditions to close other closeable objects
    }The reasoning is that if an exception were ever to happen you would be sure that the clean up would be done. In your current example you may risk having an inputstream left open. Also note that BufferedReader.readLine() returns null when its arrived at the end of its content.

  • While loop problem

    I have a problem with a while loop in this code and it is really holding me up doing my degree. I can see nothing wrong with it but perhaps someone here can help. I would be really greatful if someone could. I have commented the line where the while loop starts about a third of the way down the code.
    Thanks
    Michael
    if (ae.getSource()==client_open)
    int row=0;
    check=true;
    row=client_listing.getSelectedRow();
    try
    System.out.println("information[row][1] is "+information[row][1]);
    if(information[row][1]!=null) //if the index is not null. Comment out this if statement to troubleshoot
    try
    InetAddress inet=InetAddress.getByName(information[row][1]);
    //Create a client socket on the listeners machone on port 7070
    client_socket=new Socket(inet,7070);
    System.out.println("Client port open on 7070 ");
    //Get the output as well as the input streams on that socket
    BufferedOutputStream out=new BufferedOutputStream(client_socket.getOutputStream());
    BufferedInputStream br_socket=new BufferedInputStream(client_socket.getInputStream());
    XMLWriter writer=new XMLWriter();
    writer.requestFString("SHOWFILES"," ");
    String file_data=writer.returnRequest();
    byte file_bytes[]=file_data.getBytes();
    int file_size=file_bytes.length;
    byte b[]=new byte[1024];
    // The methos takes a byte array and it's length as parameters and return
    // a byte array of length 1024 bytes....
    add_on upload=new add_on();
    System.out.println("Class of add_on created sucessfully");
    b=upload.appropriatelength(file_bytes,file_size);
    out.write(b,0,1024);
    /*An output stream is also initialised. This is used to store all the response
    from the listener */
    BufferedOutputStream out_file=new BufferedOutputStream(new FileOutputStream("response.xml"));
    int y=0;
    byte f[]=new byte[32];
    System.out.println("Entering while loop");
    //This while loop is not working. Any ideas. It just hangs here
    while((y=br_socket.read(f,0,32))>0) //the socket input stream is read
    out_file.write(f,0,y); //written on to the file output stream, y bytes from f start @ ofset 0
    out.close();
    br_socket.close();
    out_file.close();
    System.out.println("Exited while loop and closed streams");
    catch(Exception e)
    client_socket=null;
    check=false;
    System.out.println("Didnt enter try");
    try
    client_socket.close();
    catch(Exception e)
    System.out.println("Error occuered "+e.getMessage());
    row=0;
    if(check) //If the exception occurs then do not come here
    Vector parameters=new Vector();
    // A class SParser is also used here this class has a function/method of
    // the name perform which calls the xml parser to parse the xml file
    // generated by the response from the client soket...
    // the function perform returns a Vector which has the files/directories,
    // along with their flag information and size in case of files....
    SParser sp=new SParser();
    System.out.println("SParser object created sucessfully");
    parameters=sp.perform("response.xml");
    System.out.println("Parsing finished ");
    // The vector value returned by the xml parseris then passed as one of
    // the parameters to a class named file_gui this class is responsible for
    // displaying GUI consisting of a table and some buttons along with the
    // root information and flag..
    // Initially since the class is called for the first time the parameter
    // for the root is given the name "ROOT" and the Flag is set to "0"..
    file_gui showfiles=new file_gui(parameters,information[row][1],"Root","0");
    showfiles.show();
    check=false;
    } //end if
    } // end if
    } //end try
    catch(Exception e)
    row=0;
    } //end of ae.getSource()

    Why do you think it hangs at the while loop, eh? You need to put in additional printlns to justify your assertion. It takes alot less time to diagnose if you put in specific try/catch blocks with their own printlns - even if it is not as much fun. When you get into these kinds of troubles, there is no shame in putting in prints at each statement or logical point to track down the actual fault.
    ~Bill

  • FIM MA Export errors. There is an error executing a web service object creation.

    While checking for the permission, we have figured that the Built-In Synchronization account is being deleted by an Expiration Workflow.
    FIM MA Export errors. There is an error executing a web service object creation.
    While checking for the permission, we have figured that the Built-in Synchronization account was deleted by an Expiration Workflow
    Is there a way to restore. Thanks.

    I would re-run FIM setup - I think it can re-create this account
    If you found my post helpful, please give it a Helpful vote. If it answered your question, remember to mark it as an Answer.

  • Need help on a while loop

    Hi...I am somewhat new to Java and I am trying to do a nested while loop. Basically I have a result set from a query and I want to loop though that result set BUT I need a second loop to put together 150 of the results at a time and add them to a GeoCodeRequest to send to MapInfo.....this is how I think the code should look, I need some advice if it is the proper way to loop through....
    ArrayList aal = new ArrayList();
    ServiceMessage sm = new ServiceMessage();
    ServiceMessage rsm = new ServiceMessage();
    while (rset.next())
    statRecord = statRecord + currentRecord;
    while (rset.next() && currentRecord <= 150)
    AddressEx a = new AddressEx(rset.getString(6));
    ContentColumn cc = new ContentColumn("mmhid");
    cc.setValue(rset.getString(1));
    StreetAddress streetAddress = new StreetAddress(rset.getString(3));
    streetAddress.setBuildingName(rset.getString(2));
    a.setCountrySubdivision(rset.getString(5));
    a.setMunicipality(rset.getString(4));
    a.setPostalCode(rset.getString(6));
    a.setContentColumn(0,cc);
    aal.add(a);
    currentRecord++;
    System.out.println("Inside inner while loop now..");
    System.out.println("Add 150 to request...");
    GeocodeRequestEx gr = new GeocodeRequestEx("","3.0","id",(AddressEx[])aal.toArray());
    gr.setGeocodePreference(pref);
    sm.addRequest(gr);
    System.out.println("going to geocode now...");
    try{
    LocationUtilityServiceLocator lus = new LocationUtilityServiceLocator();
    LocationUtility lu = lus.getLocationUtility(new URL(url));
    XLSType xr = lu.perform(sm.toXLS());
    rsm = new ServiceMessage(xr);......
    code goes on to do oter things but this is the basis..............
    I hope that all made since.....please help.

    I am not sure if there is a problem, that is what I am
    asking......if I have the logic correct.
    I haven't been able to test it correct because I am
    getting an:
    Exception in thread "main"
    java.lang.ClassCastException: [Ljava.lang.Object; at
    geoClient.main(geoClient.java:127)
    That means you don't have it correct.  :-)> on the following line:> > GeocodeRequestEx gr = new> GeocodeRequestEx("","3.0","id",(AddressEx[)aal.toArray
    and I haven't figured out to correct that yet......You need to use toArray(Object[]).

  • Reference in a while loop

    If you open references to a LabVIEW object, such as an application,
    control, or VI, close the references by using the Close LV Object
    Reference function. Otherwise, the reference stays in memory even
    though the VI no longer uses it.
    The above quote is from Development Guide from NI. I realized that I have been using references without closing them. Even though I have never encountered any problem, I decided to add close reference to my programs. My question is, should I put the reference and close reference vis both in a while loop and open/close every iteration or should I use open reference in front of a while loop and close it after the while loop, this way, I will have to use a shift register to keep the reference. Or whether there are some other options. Can someone give some advice?
    Thanks in advance,
    Guangde Wang
    Solved!
    Go to Solution.

    The fact that you didn't encounter problems with keeping the refs open is because LabVIEW has some quite good garbage collection.
    In the case of a for loop you should use shift registers, because a for loop can run zero (0) times after which you will have a NULL-reference.
    Ton
    Free Code Capture Tool! Version 2.1.3 with comments, web-upload, back-save and snippets!
    Nederlandse LabVIEW user groep www.lvug.nl
    My LabVIEW Ideas
    LabVIEW, programming like it should be!

  • Use the LabView time delay in a while loop instead of using the instrument inherent time loop.

    I have a zes lmg500 that I use. It has the option of continues measuring data, with a user control cycle loop (still using a while loop but the delay is coming from the instrument). The problem is that the loop time is not constant. Can I use a very short time (100ms) as the instrument cycle time but use a longer time delay in the while loop that collect the data?
    I know many instrument offer the same abilities, so the question is relevant to all of them.
    Thanks for any help
    Solved!
    Go to Solution.

    Does that measurement VI have built-in wait functionality and a timeout?
    If not, then you are simply polling the VI at 1 kHz, but I suspect that this is not the case or your Waveform Chart probably wouldn't look as you expect (getting 0's put in everytime measurement data is not available).
    I expect that if you have the instrument set up to send data at a fixed time interval (i.e. 100 ms), all the data that it is sending you will end up residing in your serial buffer (or the instrument driver will have taken it out and put it in another internal buffer), so if you come back to read it 1 sec later, then you will have 10 data points to go through.  Whether you can read them all at once with the read VI or have to call it a whole bunch of times until empty I can't say.
    What is your objective?

  • Writing a file for prescribed amount of time in a while loop after the triggering condition is met

    Hello Guys,
    I am trying to program an application in which if the trigger condition is met it should start to write the file.
    I was able to do that, but if I want it to be written for certain amount of time, and once the trigger condition is met, it should continue to write the files for prescribed amount of time. I was not able to do this. The file name should also be updated accordingly.
    I tried to with some options by keeping the creation of the file outside of the loop, if I do that then if the trigger condition is not met it will stop writing and I dont want that, as once the trigger condition is met it should be true thereafter.
    So I cant keep any thing outside the while loop, bcaz then it checks the condition of the shift register for the trigger and I have it as a false constant.
    I am attaching my application which is kind of mess and I have written in the application where I am having problems. For every iteration of while loop it makes a new file, and i dont want that, I want to write specific amount of time data to the each file.
    Please take a look at my code and help me in solving the problem. Any insights and examples on how to do this thing will be a relief to me.
    Thanks in advance.
    Regards,
    Nitin
    Attachments:
    PXI_4462_Sync_and_Stream_trigger.zip ‏192 KB

    what i am saying is to keep track of how much data you have written and whenever you need to make a new file you make 1.
    here is a vi that i just made that should show you. let me know if you need any help understanding it.
    Attachments:
    new file exemple.vi.zip ‏21 KB

  • While loop and for loop condition terminal

    Hello friends,
    I am using labview 8.6. The condition terminal of the while loop and conditional for loop is behaving in just the opposite way.
    When i wire a true to the condition terminal of my loop, the while loop continues to run when I click on run. when I wire a FALSE, it stops.
    Is there any setting change that I have to make it to get it work properly.
    Please suggest on this.
    Thanks and regards,
    Herok

    Please do NOT attach .bmp images with the extension changed to .jpg to circumvent the forum filters!
    Herok wrote:
    I am sending you the VI. I am not sure if this would help you because only in 2 computers this behaviour is seen. In others, it works as it is supposed to work.
    Whatever you are seeing must be due to some corruption or folding error. It all works fine here.
    To make sure there are no hidden objects, simply press the cleanup button which would reveal any extra stuff (which is obviously not there). Does it fix itself if you click the termination terminal an even number of times? What if you remove the bad loop and create a new one?
    Could it be you have some problems with the graphics card and the icon of the conditional terminal does not update correctly?
    Whay happens if you connect a control instead of a diagram constant?
    What is different on the computers where it acts incorrectly (different CPU (brand, model), #of cores, etc.) 
    LabVIEW Champion . Do more with less code and in less time .

  • Can we execute a query in resultset while loop

    can we execute a query in resultset while loop
    for ex:
    rs=st.executeQuery("SQL");
    while(rs.next())
    rs1=st.executequery("SQL1");
    while(rs1.next())
    }

    If you do this, you lose "rs". Create a second
    Statement object for the other query.This is right. We have done it many times, It is not the issue as long as you use different statement with in the body of the loop

  • Empty while-loop taking too much power

    Hi all!
    Would someone help me out with a better implementation of the below code. 'guard' is a class handling validation of users againt a database. I'm waiting for it to finish in an empty while loop in my GUI-class (extending JFrame). This obviously takes all CPU causing bad response time. Any smart suggestion on how to reduce this in my case?
    Thanks in advance.
    //Wait for the guard to validate user
    while(guard.getGrantedPermission() == guard.PENDING) {}
    if(guard.getGrantedPermission() == guard.ACCESS_ALLOWED) {
        setVisible(true);
    * We should be able to work with the config object since it should
    * be initialized when the password dialog prompts the user
       try {
          user = guard.getValidatedUsername();
          //Set the name of the customer
          config = new Config(user, new Date());
       } catch(NullPointerException npe) {
          npe.printStackTrace();
    }

    Don't use an empty while loop. It's a terrible construct. Listen to zurdo (the first reply). Don't use Thread.sleep() either, as it's inappropriate in your case.
    If you don't want to use Observer and Observable, then use a new Thread using the wait() and notifyAll() constructs. See the tutorial at
    http://java.sun.com/docs/books/tutorial/essential/threads/index.html
    Pay careful attention to its warnings, though.

Maybe you are looking for

  • Unit is measurement..in CO-PA

    Hi Experts, I have one confusion.... In Material master for one material i have base unit of measurement is "EA", In dimension i have KG/LT/GAL...like different kind of unit of measurements is there...In generally in T.code KE4U i have assigned Value

  • Failed appointments, terrible management, lies and...

    I've been waiting for my BT line and broadband to be installed since Dec 21st 2013. An OpenReach engineer was meant to call to connect me on Sat 21st - they failed to turn up. I phoned and was told various excuses as to why they didn't come. Was told

  • IPhoto 6.0.1 crash

    Today while editing some photos the iPhoto application crashed. Had to physically move so I closed the lid on the MacBook putting it to sleep. It didn't wake up when opening. There was a very faint shadow of the iPhoto application. Hit the power butt

  • SQL Loader - double quote within data

    Hi, I'm putting together some SQL loader scripts to load source data into a DB. The data we are receiving is comma delimited, optionally enclosed by double quotes ("). e.g. "abc","123","this is a "test"","987" The problem I've got is that some data i

  • Weird lines ...

    Hello everyone, as this is my first post I do not believe I can post a  new thread.. I am having a problem in Premiere CS3. I have  captured the video off of a dv tape.  The .avi plays fine... when it is  imported into premiere or after effects and i