multithreading - Unexpected output in concurrent file writing in java web -
i wrote simple java web application ,just included basic function register , sign in , changing password , others.
i don't use database. create file in app record users' information , database stuff.
i used jmeter stressing web application, register interface. jmeter shows result of 1000 thread right when information.txt , stores users' information, it's wrong because stores 700+ record :
but should include 1000 record, must somewhere wrong
i use singleton class write/read stuff, , add synchronized word class, insert() function used register record register information shown below: (a part of it)
public class database { private static database database = null; private static file file = null; public synchronized static database getinstance() { if (database == null) { database = new database(); } return database; } private database() { string path = this.getclass().getclassloader().getresource("/") .getpath() + "information.txt"; file = new file(path); if (!file.exists()) { try { file.createnewfile(); } catch (ioexception ex) { ex.printstacktrace(); } } } public void insert(string account, string password, string username) { randomaccessfile infofile = null; try { infofile = new randomaccessfile(file, "rw"); string record; long offset = 0; while ((record = infofile.readline()) != null ) { offset += record.getbytes().length+2; } infofile.seek(offset); record = account+"|"+password+"|"+username+"\r\n"; infofile.write(record.getbytes()); infofile.close(); } catch (ioexception e) { e.printstacktrace(); } { if (infofile != null) { try { infofile.close(); } catch (ioexception ex) { ex.printstacktrace(); } } } } }
the question why happened , synchronized thread safe, why lost many data , blank line inserted it, correct !
you synchronizing getinstance() method, not insert() method. makes retrieval of instance of database thread-safe, not write operation.
Comments
Post a Comment