Results 1 to 4 of 4
Like Tree1Likes
  • 1 Post By kjkrum

Thread: Testing multithreading code needed!

  1. #1
    heatblazer is offline Senior Member
    Join Date
    Nov 2012
    Posts
    131
    Rep Power
    0

    Default Testing multithreading code needed!

    Hello,
    I need somebody quite fond of threads to test this piece of code and tell me if I`ve made the threading right. Help will be appreciated.
    Java Code:
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JList;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JLabel;
    import javax.swing.text.*;
    import javax.swing.JFormattedTextField;
    
    
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.FlowLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowListener;
    import java.awt.event.WindowEvent;
    
    import java.awt.Rectangle;
    import java.awt.Window;
    
    import java.io.FileOutputStream;
    import java.io.FileInputStream;
    import java.io.ObjectOutputStream;
    import java.io.ObjectInputStream;
    import java.io.PrintWriter;
    import java.io.Serializable;
    import java.io.File;
    
    import java.util.ArrayList;
    import java.util.Set;
    
    public class MainFrame extends JFrame implements Serializable {
    			/*this class is made for serilization purpose */				
    			private static final long serialVersionUID = 1L;			 
    			class Storage  implements Serializable {
    					 private static final long serialVersionUID = 2L;
    					ArrayList<Person> empl = new ArrayList<Person>();
    					public void addEmp(Person p) {
    							empl.add(p);
    					}
    					public ArrayList<Person> getEmps() {
    							return empl;
    						}
    				} //end INNER 1
    				//Private containers
    				JList list = new JList();
    				Storage store = new Storage(); /* bug frammed if missing TMP.ser 
    												  store will be null so it won`t be able
    												  to interact with add new employee frame 
    												  set not null reference to store !
    												  */
    												  
    /* ################################### MAIN FRAME CTOR */
    				private void checkSerializeFile(final String filename) {
    					synchronized(this) {
    					try {
    					new Thread(new Runnable() {
    						@Override
    						public void run() {
    							if ( new File(filename).exists() || new File(filename).canWrite() ) {
    								System.out.format("File exist and is writable\n");
    								} else {
    									System.err.println("Can`t find file! Warning!");
    									}
    						}
    						}).start();
    						} catch (Exception e4) { }
    						}
    					}
    
    				public MainFrame() {
    						//call JFrame();
    						super();
    						// add listener to MAIN FRAME
    						addWindowListener(new WindowListener() {
    							public void windowDeactivated(WindowEvent e) {}
    							public void windowOpened(WindowEvent e) {}
    							public void windowIconified(WindowEvent e) {}
    							public void windowDeiconified(WindowEvent e) {}
    							public void windowClosing(WindowEvent e) {
    								
    							}
    							public void windowActivated(WindowEvent e) {}
    							@Override 
    							public void windowClosed(WindowEvent we) { 
    								threadPurge();
    							}
    							}); // CLOSE MAN FRAME LISTENER
    												
    						setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    						setTitle("Payment program testing");
    						setSize(600, 320);
    						checkSerializeFile("TMP.ser");
    						restoreSer();
    						//Buttons panel
    						JPanel buttonPanel = new JPanel();
    						
    						JButton addButton = new JButton("Add new person");
    						addButton.addActionListener(new ActionListener() {
    								@Override
    								public void actionPerformed(ActionEvent e) {
    										//iniate new thread here
    										System.out.println("Adding...");
    										final JFrame adding = new JFrame();
    										//enable control on closing
    										adding.addWindowListener(new WindowListener() {
    												public void windowDeactivated(WindowEvent e) {}
    												public void windowOpened(WindowEvent e) {}
    												public void windowIconified(WindowEvent e) {}
    												public void windowDeiconified(WindowEvent e) {}
    												public void windowClosing(WindowEvent e) {}
    												public void windowActivated(WindowEvent e) {}
    												@Override
    												public void windowClosed(WindowEvent we) {
    													Set<Thread> tmp = (Thread.getAllStackTraces()).keySet();
    													Thread[] tmps = tmp.toArray(new Thread[tmp.size()]);
    													for (int i=0; i < tmps.length; i++) {
    														System.out.println("Threads: "+tmps[i].getName());
    														if ( tmps[i].getName().equals("ADD_THREAD") ) {
    															tmps[i].interrupt();
    															}
    														}
    												}
    										});
    														
    														
    														
    										adding.setLayout(new BorderLayout());
    										adding.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    										adding.setSize(320,240);
    										JPanel inputWorker = new JPanel(new GridLayout(0,1));
    										final JLabel fnamel = new JLabel("First name:");
    										final JLabel snamel = new JLabel("Second name: ");
    										final JLabel jobl = new JLabel("Job: ");
    										final JFormattedTextField fname1 = new JFormattedTextField();
    										fname1.setColumns(10);
    										final JFormattedTextField sname1 = new JFormattedTextField();
    										sname1.setColumns(10);
    										String[] occs = {"worker", "Maintenance", "engeneer", "support"};
    										final JComboBox job = new JComboBox(occs);
    										//button event setup
    										final JButton addButton1 = new JButton("Add");
    										addButton1.setEnabled(false);
    										addButton1.addActionListener(new ActionListener() {
    												
    												@Override
    												public void actionPerformed(ActionEvent saveenvnt) {
    														try {
    																store.addEmp(new Person(fname1.getText(), sname1.getText(), "some work" ));
    																PrintWriter outf = new PrintWriter("empl.txt");															
    																for (int i=0; i < store.getEmps().size(); i++) { outf.println(((store.getEmps()).get(i)).getName()); }	
    																outf.close();
    																
    																
    																
    														} catch (Exception saveex) { }
    														finally { adding.dispose(); }
    												}
    										}); //close ADD button 
    														
    														
    										inputWorker.add(fnamel);
    										inputWorker.add(fname1);
    										inputWorker.add(snamel);
    										inputWorker.add(sname1);
    										inputWorker.add(jobl);
    										inputWorker.add(job);
    										inputWorker.add(addButton1);
    										adding.add(inputWorker);
    										adding.setVisible(true);
    										
    										/* check if both fields are input and then unlock button ADD */
    										try {
    												new Thread(new Runnable() {
    														@Override
    														public void run() {
    																Thread.currentThread().setName("ADD_THREAD");
    																while (
    																		sname1.getText().equals("") ||
    																		fname1.getText().equals("")
    																) { /*some debug message here */ }
    																addButton1.setEnabled(true);
    																
    														}
    												}).start();
    										} catch (Exception eeee) {}
    										  finally {   }
    										
    								}
    						});
    						
    						JButton viewButton = new JButton("View personel");
    						viewButton.addActionListener(new ActionListener() {
    								@Override
    								public void actionPerformed(ActionEvent e) {
    										//iniate new thread here
    									//also make it synchro
    									}
    						});
    						
    						JButton removeButton = new JButton("Delete a person");
    						removeButton.addActionListener(new ActionListener() {
    								@Override
    								public void actionPerformed(ActionEvent e) {
    										//iniate new thread here
    								}
    						});
    						
    						
    						JButton saveButton = new JButton("Record database");
    						saveButton.addActionListener(new ActionListener() {
    								@Override
    								public void actionPerformed(ActionEvent e) {
    										//iniate new thread here
    										//also make it synchro
    										synchronized(this) {
    										System.out.println("Saving object...");
    										try { 
    										new Thread(new Runnable() {
    										@Override
    										public void run() {
    										
    										Thread.currentThread().setName("SAVE_THREAD");
    										if ( store.getEmps().isEmpty() ) { System.err.println("No objects to save"); return ; }
    										try {
    											synchronized (this) {
    												ObjectOutputStream os = new ObjectOutputStream(
    												new FileOutputStream("TMP.ser"));	
    												os.writeObject(store);
    												os.close(); 
    											}
    										} catch (Exception ex) { };
    									}}).start();
    								} catch (Exception e2) {}
    							} }
    						});
    						
    				//ADD COMPONENTS TO MAIN FRAME HERE ####################################
    						buttonPanel.add(addButton);
    						buttonPanel.add(viewButton);
    						buttonPanel.add(removeButton);
    						buttonPanel.add(saveButton);
    						//
    						/* JText area */
    						JPanel listPanel = new JPanel();
    												
    						
    						listPanel.add(list);
    						
    						
    						//the layout is FlowLayout
    						setLayout(new FlowLayout());
    						add(buttonPanel);
    						add(listPanel, BorderLayout.CENTER);
    						//set visible
    						setLocationRelativeTo(null); //center it
    						
    								
    						setVisible(true);
    						
    								
    				}
    				
    				private void restoreSer() {
    					
    					synchronized(this) {
    										try {
    											
    											new Thread(new Runnable() {
    										
    										@Override
    										public void run() {
    										System.out.println("##"+Thread.currentThread().toString());
    										
    										if ( Thread.currentThread().equals("Restore_SER_Thread") ) {
    												Thread.currentThread().stop() ; }
    										Thread.currentThread().setName("Restore_SER_Thread");										
    										try {
    												if ( new File("TMP.ser").exists() ) {
    												System.out.println("Now restoring object...");
    												FileInputStream restor = new FileInputStream("TMP.ser");
    												ObjectInputStream objects = new ObjectInputStream(restor);
    												System.out.println("Passed ObjectInputStream "+objects.toString());							
    											
    												store   = (Storage) objects.readObject();
    												
    												System.out.println("Passed Object");
    												for (int i=0; i < store.getEmps().size(); i++) {
    													System.out.println((store.getEmps().get(i)).getName()); }
    												restor.close();
    												objects.close();
    												//list = new JList(tmp);
    												//list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
    												} else { 
    													System.err.println("Warning! You are missing an essential temporal file! Contact the sys admin!");													
    													return ; }
    										} catch(Exception eee) {eee.printStackTrace();}
    									}	 
    									}).start(); 
    									} catch (Exception e1) { }
    									
    								}
    							
    							}//end synchro
    
    				public void threadPurge() {
    					Set<Thread> tmp = (Thread.getAllStackTraces()).keySet();
    					Thread[] tmps = tmp.toArray(new Thread[tmp.size()]);
    						
    							for (int i=0; i < tmps.length; i++) {
    								System.out.println("Threads: "+tmps[i].getName());
    								if ( tmps[i].isAlive() ) tmps[i].interrupt();
    								}
    					}
    				
    				public static void main(String[] args) {
    						MainFrame mf = new MainFrame();
    						
    				}
    }
    Regards!

  2. #2
    rfq
    rfq is offline Member
    Join Date
    Mar 2012
    Location
    Novosibirsk, Russia
    Posts
    15
    Rep Power
    0

    Default Re: Testing multithreading code needed!

    "Made right" means the code works as expected. How can we tell you if it is done right, when we don't know your expectations?

  3. #3
    heatblazer is offline Senior Member
    Join Date
    Nov 2012
    Posts
    131
    Rep Power
    0

    Default Re: Testing multithreading code needed!

    You have the point. Well I am just asking to test on different machines and to tell me if it`s good working, it`s still unfinished. But, really, I did not provide "break points". Will do better next time.

  4. #4
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    6

    Default Re: Testing multithreading code needed!

    The problem with threads is that many JVMs provide stronger guarantees than they are required to. So just because it works on one system or a dozen systems doesn't necessarily mean it's right.

    At a glance I can see a few things wrong. On line 217, you're syncing on the ActionListener, which is pointless because aside from System.out, you're only operating on local variables. On line 227, the Thread is syncing on itself, which is pointless since each thread will sync on a different object. On line 277 you're using Thread.stop(), which is always wrong. See Thread (Java Platform SE 6). On line 317 you're instantiating a Swing container in the main thread, which is one of those things you can usually get away with, but still wrong. You should only create an manipulate Swing components on the UI thread.
    Last edited by kjkrum; 05-09-2013 at 09:15 AM.
    sevoxx likes this.
    Get in the habit of using standard Java naming conventions!

Similar Threads

  1. Whitebox testing and testing tables, help please
    By Stefano in forum New To Java
    Replies: 2
    Last Post: 02-07-2013, 05:02 AM
  2. Java simple testing needed
    By heatblazer in forum New To Java
    Replies: 0
    Last Post: 12-13-2012, 06:08 AM
  3. Java Downloader.MultiThreading/in part downloading ....Help Needed
    By haafiz786 in forum Threads and Synchronization
    Replies: 3
    Last Post: 03-15-2012, 09:26 AM
  4. Junit testing, testing list<e> interface
    By mackavelirip in forum New To Java
    Replies: 0
    Last Post: 10-05-2011, 06:08 AM
  5. Help Testing My Homework Code
    By sehudson in forum New To Java
    Replies: 1
    Last Post: 03-01-2011, 07:23 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •