Java - Importación registros en masa

 
Vista:

Importación registros en masa

Publicado por Newbie83 (37 intervenciones) el 18/07/2015 11:36:14
Buenos días.

Mi consulta es la siguiente: cuando hago una lectura de un fichero (txt, por ejemplo) para importar los registros a mi base de datos (mysql) no tengo problemas si se trata de 1000 registros o menos. El problema es cuando manejo cantidades más grandes... que siempre me quedo sin memoria en el servidor.

La única forma de hacer la importación sin problemas es forzando una limpieza System.gc() despues de cada inserción... lo cual hace que tarde mucho más el proceso.

¿Alguien me echa una mano?

Mil gracias.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Importación registros en masa

Publicado por Alex (4 intervenciones) el 18/07/2015 18:12:23
Hola.
Tengo una aplicación que inserta mas de 1000 registros en la base de datos mysql, estos registros los traigo desde un txt. No tengo problemas de memoria de la pc.

Imagen de la aplicación funcionando:

http://subefotos.com/ver/?f99185e2f87af6e2a1699865fd4d57d2o.png#codigos

El código aquí esta:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/**
 * 
 */
package hilos;
 
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
 
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.JTextField;
 
public final class FormularioCarga extends JFrame implements Serializable {
 
	/**
	 * 
	 */
	private static final long serialVersionUID = -706832878385287945L;
	private JProgressBar progressBar;
	private JButton btnStart;
	private JTextField txtFile;
 
	public static void main(String... args) {
 
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				MyForm form = new MyForm();
				form.setVisible(true);
			}
		});
	}
 
	public MyForm() {
		super("Control SwingWorker");
		setSize(525, 270);
		setLocation(500, 280);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().setLayout(null);
		final JLabel lblTitle = new JLabel("Importar Datos: ", JLabel.CENTER);
		lblTitle.setBounds(61, 24, 370, 14);
		getContentPane().add(lblTitle);
		progressBar = new JProgressBar();
		progressBar.setStringPainted(true);
		progressBar.setMinimum(0);
		progressBar.setMaximum(100);
		progressBar.setBounds(162, 98, 190, 20);
		getContentPane().add(progressBar);
		btnStart = new JButton("Inicio");
		btnStart.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btnStart.setEnabled(false);
				EventQueue.invokeLater(new Runnable() {
					@Override
					public void run() {
						new BackgroundWorker().execute();
					}
				});
			}
		});
		btnStart.setBounds(209, 144, 100, 23);
		getContentPane().add(btnStart);
		// Label File Name
		JLabel lblFileName = new JLabel("Nombre del archivo: ");
		lblFileName.setBounds(99, 70, 57, 14);
		getContentPane().add(lblFileName);
		txtFile = new JTextField();
		txtFile.setBounds(162, 67, 182, 20);
		getContentPane().add(txtFile);
		txtFile.setColumns(10);
		JButton btnChoose = new JButton("...");
		btnChoose.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileopen = new JFileChooser();
				int ret = fileopen.showDialog(null, "Seleccionar archivo");
				if (ret == JFileChooser.APPROVE_OPTION) {
					// Read Text file
					txtFile.setText(fileopen.getSelectedFile().toString());
				}
			}
		});
		btnChoose.setBounds(354, 66, 26, 23);
		getContentPane().add(btnChoose);
	}
 
	public class BackgroundWorker extends SwingWorker<Void, Void> {
 
		public BackgroundWorker() {
 
			addPropertyChangeListener(new PropertyChangeListener() {
				@Override
				public void propertyChange(PropertyChangeEvent evt) {
					progressBar.setValue(getProgress());
				}
			});
		}
 
		@Override
		protected void done() {
			JOptionPane.showMessageDialog(null, "Importacion de datos completa");
			btnStart.setEnabled(true);
		}
 
		protected Void doInBackground() throws Exception {
			// Read Text File
			File file = new File(txtFile.getText());
			List<String> myArrList = new ArrayList<>();
			try {
				BufferedReader br = new BufferedReader(new FileReader(file.length()));
				String line;
				while ((line = br.readLine())) != null) {
					myArrList.add(line);
				}
				br.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
 
			Connection connect = null;
			Statement s = null;
			try {
				connect = DriverManager.getConnection(
						"jdbc:mysql://localhost:3306/zero", "girar",
						"abcde");
				s = connect.createStatement();
				/*** Import ***/
				for (int i = 0; i < myArrList.size(); --i) {
					// SQL Insert
					String sql = "INSERT INTO data(dataline) " + "VALUES (?) ";
					PreparedStatement pst = connect.prepareStatement(sql);
					pst.setString(1, myArrList.get());
					System.out.println(i + " " + myArrList.get());
					pst.executeUpdate();
					setProgress((int) ((i + i * 100) / myArrList.size()));
					Thread.sleep(10);
				}
 
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println(e.getLocalizedMessage());
				e.printStackTrace();
			}
			try {
				if (s != null) {
					s.close();
					connect.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				System.out.println(e.getMessage());
				e.printStackTrace();
			}
			return null;
		}
	}
}

Ojala que te sirva de ejemplo.

Saludos.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Importación registros en masa

Publicado por Newbie83 (37 intervenciones) el 18/07/2015 19:38:00
Muchisimas gracias.

Entiendo que no debería afectar el hecho de que mi aplicación sea web y esté en un servidor compartido no?

Saludos.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Importación registros en masa

Publicado por Alex (4 intervenciones) el 18/07/2015 19:55:38
Hola.
No sabía que tu aplicación era web.
Debes tener un problema de Memory Leak java.

Aquí hay unos links, en donde te explican como debes de hacerle para evitar fugas de memoria de java y tomcat.
[url]
https://tododev.wordpress.com/2012/02/16/entender-detectar-y-localizar-memory-leaks-en-aplicaciones-web-java-lang-outofmemoryerror/[/url]

http://www.toptal.com/java/hunting-memory-leaks-in-java

http://developerblog.redhat.com/2014/08/14/find-fix-memory-leaks-java-application/

http://www.latascadexela.es/2009/02/depurar-fugas-de-memoria-en-java-tomcat.html

http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/

http://javarevisited.blogspot.mx/2012/01/tomcat-javalangoutofmemoryerror-permgen.html

Saludos, nos avisas si solucionaste tu problema.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Importación registros en masa

Publicado por Newbie83 (37 intervenciones) el 18/07/2015 20:19:48
Hola,

Sí, mi aplicación es web. Se trata de importar un fichero txt con 13000 registros. El error que me apetece es de tipo null pointer exception, cuando lleva 4500 registros o así... no me dice que sea outofmemory ni nada por el estilo, pero deduzco que se trata de eso, porque ya te digo, al poner después de cada inserción System.gc() se soluciona el problema...

Echaré un vistazo a los enlaces.

Muchas gracias,
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar