GZipOutputStream problem!

Hello,
I am running into a weird problem which is intermittent.
I am trying to generate an encrypted URL from an input string.
I am using URLEncoding, MD5Checksum, zipping (for compression) and using BlowFish for encryption. The input string is a variable length string though in this case, the problem is showing up in a string of fixed length.
The compression method uses GZipOutputStream with ByteArrayOutPutStream as the underlying stream to compress data.
This compressed data is then used as the input to BlowFish for getting the encrypted result which is then Base64 and URL encoded.
The problem is that if the encryption program is called in a loop with the same payload string as input, the encryption program sometimes generates an invalid URL. Following is the zip utility.
private static byte[] zipIt ( String parameterString )
        byte[] zipped;
        try {
            ByteArrayOutputStream catcher = new ByteArrayOutputStream();
            GZIPOutputStream gzipOut = new GZIPOutputStream( catcher );
            byte[] bytesToZip = parameterString.getBytes();
            gzipOut.write( bytesToZip, 0, bytesToZip.length );
            gzipOut.close();
            return catcher.toByteArray();
        catch ( Exception ioe ) {
            ioe.printStackTrace();
            return "error".getBytes();
    }The length of the compressed string generated by this method is different (for the most part it is the same) on certain iterations.
Is there an issue with the GZipOutputStream or the ByteArrayOutputStream? By the way, I tried this using both JDK 1.3.3 and 1.5.03.
Thanks in advance,
coderiyer

Thanks for the response. For Base64, an open source class is being used. This http://iharder.sourceforge.net/current/java/base64/ is the link to this class. Version 1.3.6 is being used. What I don't understand is even if I don't remove the URLDecode on the decryption side after removing URLencode on the encryption end, it still works. Following is the legacy code for encryption/decryption. By the way, to answer your earlier question, the client is having problems in using the encrypted URL when it gets decrypted but it has been found that the encryption was incorrect in the first place.
Thanks for your help again.
coderiyer
public static String encryptPayload (String payload, String authKey) {
try {
// Steps for creating an encrypted URL:
// 1 - Calculate the checksum
// 2 - Concatenate the checksum and payload
// 3 - URL Encode
// 4 - Compress the string using zipIt (GZIP)
// 5 - Encrypt using Blowfish and SunJCE
// 6 - Base 64 encode
// 7 - URL encode
// 8 - Return the complete string
BlowFishUtil bfUtil = new BlowFishUtil();
logger.debug("---------------------------------------");
logger.debug("encryptPayload payload");
logger.debug(payload);
logger.debug("authKey");
logger.debug(authKey);
logger.debug("---------------------------------------");
String sCheckSum = getMD5Checksum(payload);
String encodeBuffer = sCheckSum + payload;
logger.debug("---------------------------------------");
logger.debug("sCheckSum");
logger.debug(sCheckSum);
logger.debug("---------------------------------------");
encodeBuffer = URLEncoder.encode(encodeBuffer);
logger.debug("---------------------------------------");
logger.debug("URLEncoder.encode");
logger.debug(encodeBuffer);
logger.debug("---------------------------------------");
byte[] aryEncodeBuf = zipIt(encodeBuffer);
logger.debug("---------------------------------------");
logger.debug("zipIt");
logger.debug(new String(aryEncodeBuf));
logger.debug("---------------------------------------");
aryEncodeBuf = bfUtil.encryptSecretKey(authKey.getBytes(),aryEncodeBuf);
logger.debug("---------------------------------------");
logger.debug("encryptSecretKey");
logger.debug(new String(aryEncodeBuf));
logger.debug("---------------------------------------");
encodeBuffer = Base64.encodeBytes(aryEncodeBuf);
logger.debug("---------------------------------------");
logger.debug("Base64.encodeBytes");
logger.debug(encodeBuffer);
logger.debug("---------------------------------------");
encodeBuffer = URLEncoder.encode(encodeBuffer);
logger.debug("---------------------------------------");
logger.debug("URLEncoder.encode");
logger.debug(encodeBuffer);
logger.debug("---------------------------------------");
return encodeBuffer;
catch (Exception e) {
logger.debug("[PDFWebApiDelegate:encryptPayload] - Exception : " + e );
return null;
public static String decryptPayload (String payload, String authKey) {
try {
// Steps for decrypted a URL:
// 1 - URL decode
// 2 - Base 64 encode
// 3 - Decrypt using Blowfish and SunJCE
// 4 - Decompress the string using unzipIt (GZIP)
// 5 - Strip off the checksum, calculate the checksum from the payload
// and verify they match
// 6 - Return the decrypted payload
String decodeBuffer = "";
BlowFishUtil bfUtil = new BlowFishUtil();
logger.debug("---------------------------------------");
logger.debug("decryptPayload payload");
logger.debug(payload);
logger.debug("authKey");
logger.debug(authKey);
logger.debug("---------------------------------------");
decodeBuffer = URLDecoder.decode(payload);
logger.debug("---------------------------------------");
logger.debug("URLDecoder.decode");
logger.debug(decodeBuffer);
logger.debug("---------------------------------------");
decodeBuffer = Base64.decodeToString(decodeBuffer);
logger.debug("---------------------------------------");
logger.debug("Base64.decodeToString");
logger.debug(decodeBuffer);
logger.debug("---------------------------------------");
byte[] aryDecodeBuf = bfUtil.decryptSecretKey(authKey.getBytes(), decodeBuffer.getBytes());
logger.debug("---------------------------------------");
logger.debug("decryptSecretKey");
logger.debug(new String(aryDecodeBuf));
logger.debug("---------------------------------------");
aryDecodeBuf = unzipIt(aryDecodeBuf);
logger.debug("---------------------------------------");
logger.debug("unzipIt");
logger.debug(new String(aryDecodeBuf));
logger.debug("---------------------------------------");
String sBuf = new String(aryDecodeBuf);
logger.debug("---------------------------------------");
logger.debug("new String(aryDecodeBuf)");
logger.debug(sBuf);
logger.debug("---------------------------------------");
sBuf = URLDecoder.decode(sBuf);
logger.debug("---------------------------------------");
logger.debug("URLDecoder.decode");
logger.debug(sBuf);
logger.debug("---------------------------------------");
int iPos = sBuf.indexOf("st=");
logger.debug("---------------------------------------");
logger.debug("iPos of st=");
logger.debug(String.valueOf(iPos));
logger.debug("---------------------------------------");
if (iPos>=0) {
String sURLCheckSum = sBuf.substring(0,iPos);
sBuf = sBuf.substring(iPos,sBuf.length());
String sCheckSum = getMD5Checksum(sBuf);
if (!sCheckSum.equals(sURLCheckSum)) {
logger.debug("[PDFWebApiDelegate:decryptPayload] ERROR: Checksums do not match.");
logger.debug("---------------------------------------");
logger.debug("urlchecksum");
logger.debug(sURLCheckSum);
logger.debug("calcedchecksum");
logger.debug(sCheckSum);
logger.debug("sBuf");
logger.debug(sBuf);
logger.debug("---------------------------------------");
return new String(sBuf);
catch (Exception e) {
logger.debug("[PDFWebApiDelegate:decryptPayload] - Exception : " + e );
return null;
* Creates an MD5 checksum for the passed <code>String</code>
* @param mess The message for which we are determining the check sum.
* @return String The checksum string
private static String getMD5Checksum( String mess ){
String hexHashCode = "";
String hashCode = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] message = mess.getBytes("UTF-8");
md.update( message );
byte[] hash = md.digest();
for ( int i=0; i < hash.length; i++ ){
int x = hash[i] & 0xFF;
if (x < 0x10) {
hexHashCode += "0";
hexHashCode += (Integer.toHexString(x));
hashCode += hash[i]+" _ ";
catch (Exception e) {
e.printStackTrace();
return "error";
return hexHashCode;
private static byte[] zipIt ( String parameterString )
byte[] zipped;
try {
ByteArrayOutputStream catcher = new ByteArrayOutputStream();
GZIPOutputStream gzipOut = new GZIPOutputStream( catcher );
byte[] bytesToZip = parameterString.getBytes();
gzipOut.write( bytesToZip, 0, bytesToZip.length );
gzipOut.close();
return catcher.toByteArray();
catch ( Exception ioe ) {
ioe.printStackTrace();
return "error".getBytes();
private static byte[] unzipIt ( byte[] buffer ) {
ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
ByteArrayInputStream inBuffer = new ByteArrayInputStream(buffer);
try {
GZIPInputStream gzip = new GZIPInputStream(inBuffer);
byte[] tmpBuffer = new byte[256];
int n;
while ((n = gzip.read(tmpBuffer)) >= 0) {
outBuffer.write(tmpBuffer, 0, n);
return outBuffer.toByteArray();
catch (Exception e) {
logger.debug("[PDFWebApiDelegate:unzipIt] - Exception : "+e);
return null;
}

Similar Messages

  • GZip / GZIPOutputStream problem.

    Hi guys.
    This is my problem:
    I'm getting some information from database, formatting it to a String and sending back to the DB for future use.
    Is there any way to GZip it, store GZipped info in the DB, and when sending to client use GZIPOutputStream ?
    Now I save it as a String, and use this code for outputting:
    GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
    response.setHeader("Content-Encoding", "gzip");
    gzos.write(sdl.outPut.toString().getBytes());
    gzos.close();
    Any help will be appriciated,
    Thanks in advance, Vadim.

    Thanks.
    But how?
    What should I use for OutputStream?
    When I do gzos.write() it sends it to the response, so I should change this line: GZIPOutputStream(response.getOutputStream()) for something else...
    Any ideas?

  • Problem in flushing an Object - ObjectOutputzStream on GZipOutputStream

    Hi
    I have the following code, which is meant for writting a serialized java objects into a file.
    FileOutputStream outFile = new FileOutputStream(fileName);
    GZIPOutputStream gzipOut = new GZIPOutputStream(outFile);
    ObjectOutputStream out = new ObjectOutputStream(gzipOut);The following two lines will be called multiple times (i.e. whenever I receive java object for writing)
    out.writeObject(msg); //msg is a serialized java object
    out.flush();
    Here I'm not seeing the object written into the file when I call flush.
    Only when I close the ObjectOutputStream the objects are getting written to the file.
    Can anybody give me a solution how to write each object lively to the file whenever I receive it.
    Thanks,
    Bhaskar

    You will need to do an out.reset() before your out.write() because and ObjectOutputStream will cache the array list referenced by 'a' the first time it is written and then just write a reference to it after that. The reset() clears the cache.
    Note - you might also want to do a clear() on the array list before adding the two values as it will get bigger and bigger and bigger.
    Message was edited by:
    sabre150

  • Problem in using socket streams with encryption and decryption

    Hi,
    I am developing a client/server program with encryption and decryption at both end. While sending a message from client it should be encrypted and at the receiving end(server) it should be decrypted and vice versa.
    But while doing so i got a problem if i use both encryption and decryption at both ends. But If i use only encryption at one (only outputstream) and decryption at other end(only inputstream) there is no problem.
    Here is client/server pair of programs in which i am encrypting the outputstream of the socket in client side and decrypting the inputstream of the socket in server side.
    serverSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class serverSocketDemo
         public static void main(String args[])
              try
              {                    //server listening on port 2000
                   ServerSocket server=new ServerSocket(2000);
                   while (true)
                        Socket theConnection=server.accept();
                        System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                        System.out.println("Connection request from : "+theConnection.getInetAddress());
                        //Input starts from here
                        Reader in=new InputStreamReader(getNetInStream(theConnection.getInputStream()),"ASCII");
                        StringBuffer strbuf=new StringBuffer();
                        int c;
                        while (true)
                             c=in.read();
                             if(c=='\n' || c==-1)
                                  break;
                             strbuf.append((char)c);     
                        String str=strbuf.toString();
                        System.out.println("Message from Client : "+str);
                        in.close();               
                        theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static BufferedInputStream getNetInStream(InputStream in) throws Exception
              // register the provider that implements the algorithm
              Provider sunJce = new com.sun.crypto.provider.SunJCE( );
              Security.addProvider(sunJce);
              // create a key
              byte[] desKeyDataDec = "This encryption can not be decrypted".getBytes();
              DESKeySpec desKeySpecDec = new DESKeySpec(desKeyDataDec);
              SecretKeyFactory keyFactoryDec = SecretKeyFactory.getInstance("DES");
              SecretKey desKeyDec = keyFactoryDec.generateSecret(desKeySpecDec);
              // use Data Encryption Standard
              Cipher desDec = Cipher.getInstance("DES");
              desDec.init(Cipher.DECRYPT_MODE, desKeyDec);
              CipherInputStream cin = new CipherInputStream(in, desDec);
              BufferedInputStream bin=new BufferedInputStream(new GZIPInputStream(cin));
              return bin;
    clientSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class clientSocketDemo
         public static void main(String args[])
              try
                   Socket theConnection=new Socket("localhost",2000);
                   System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                   System.out.println("Connecting to : "+theConnection.getInetAddress());
                   //Output starts from here               
                   OutputStream out=getNetOutStream(theConnection.getOutputStream());
                   out.write("Please Welcome me\n".getBytes());
                   out.flush();
                   out.close();
                   theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static OutputStream getNetOutStream(OutputStream out) throws Exception
              // register the provider that implements the algorithm
              Provider sunJce = new com.sun.crypto.provider.SunJCE( );
              Security.addProvider(sunJce);
              // create a key
              byte[] desKeyDataEnc = "This encryption can not be decrypted".getBytes();
              DESKeySpec desKeySpecEnc = new DESKeySpec(desKeyDataEnc);
              SecretKeyFactory keyFactoryEnc = SecretKeyFactory.getInstance("DES");
              SecretKey desKeyEnc = keyFactoryEnc.generateSecret(desKeySpecEnc);
              // use Data Encryption Standard
              Cipher desEnc = Cipher.getInstance("DES");
              desEnc.init(Cipher.ENCRYPT_MODE, desKeyEnc);
              CipherOutputStream cout = new CipherOutputStream(out, desEnc);
              OutputStream outstream=new BufferedOutputStream(new GZIPOutputStream(cout));
              return outstream;
    Here is client/server pair in which i use both encrypting outpustream and decrypting inputstream at both ends.
    serverSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class serverSocketDemo
         private Cipher desEnc,desDec;
         serverSocketDemo()
              try
                   // register the provider that implements the algorithm
                   Provider sunJce = new com.sun.crypto.provider.SunJCE( );
                   Security.addProvider(sunJce);
                   // create a key
                   byte[] desKeyData = "This encryption can not be decrypted".getBytes();
                   DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
                   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
                   SecretKey desKey = keyFactory.generateSecret(desKeySpec);
                   desEnc = Cipher.getInstance("DES");
                   desEnc.init(Cipher.ENCRYPT_MODE, desKey);
                   desDec = Cipher.getInstance("DES");
                   desDec.init(Cipher.DECRYPT_MODE, desKey);               
              catch (javax.crypto.NoSuchPaddingException e)
                   System.out.println(e);          
              catch (java.security.NoSuchAlgorithmException e)
                   System.out.println(e);          
              catch (java.security.InvalidKeyException e)
                   System.out.println(e);          
              catch(Exception e)
                   System.out.println(e);
              startProcess();
         public void startProcess()
              try
                   ServerSocket server=new ServerSocket(2000);
                   while (true)
                        final Socket theConnection=server.accept();
                        System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                        System.out.println("Connection request from : "+theConnection.getInetAddress());
                        Thread input=new Thread()
                             public void run()
                                  try
                                       //Input starts from here
                                       Reader in=new InputStreamReader(new BufferedInputStream(new CipherInputStream(theConnection.getInputStream(), desDec)),"ASCII");
                                       StringBuffer strbuf=new StringBuffer();
                                       int c;
                                       while (true)
                                            c=in.read();
                                            if(c=='\n'|| c==-1)
                                                 break;
                                            strbuf.append((char)c);     
                                       String str=strbuf.toString();
                                       System.out.println("Message from Client : "+str);
                                  catch(Exception e)
                                       System.out.println("Error caught inside input Thread : "+e);
                        input.start();
                        Thread output=new Thread()
                             public void run()
                                  try
                                       //Output starts from here
                                       OutputStream out=new BufferedOutputStream(new CipherOutputStream(theConnection.getOutputStream(), desEnc));
                                       System.out.println("it will not be printed");
                                       out.write("You are Welcome\n".getBytes());
                                       out.flush();
                                  catch(Exception e)
                                       System.out.println("Error caught inside output Thread : "+e);
                        output.start();
                        try
                             output.join();
                             input.join();
                        catch(Exception e)
                        theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static void main(String args[])
              serverSocketDemo server=new serverSocketDemo();          
    clientSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class clientSocketDemo
         private Cipher desEnc,desDec;
         clientSocketDemo()
              try
                   // register the provider that implements the algorithm
                   Provider sunJce = new com.sun.crypto.provider.SunJCE( );
                   Security.addProvider(sunJce);
                   // create a key
                   byte[] desKeyData = "This encryption can not be decrypted".getBytes();
                   DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
                   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
                   SecretKey desKey = keyFactory.generateSecret(desKeySpec);
                   desEnc = Cipher.getInstance("DES");
                   desDec = Cipher.getInstance("DES");
                   desEnc.init(Cipher.ENCRYPT_MODE, desKey);
                   desDec.init(Cipher.DECRYPT_MODE, desKey);               
              catch (javax.crypto.NoSuchPaddingException e)
                   System.out.println(e);          
              catch (java.security.NoSuchAlgorithmException e)
                   System.out.println(e);          
              catch (java.security.InvalidKeyException e)
                   System.out.println(e);          
              catch(Exception e)
                   System.out.println(e);
              startProcess();
         public void startProcess()
              try
                   final Socket theConnection=new Socket("localhost",2000);
                   System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                   System.out.println("Connecting to : "+theConnection.getInetAddress());
                   Thread output=new Thread()
                        public void run()
                             try
                                  //Output starts from here               
                                  OutputStream out=new BufferedOutputStream(new CipherOutputStream(theConnection.getOutputStream(), desEnc));
                                  out.write("Please Welcome me\n".getBytes());
                                  out.flush();
                             catch(Exception e)
                                  System.out.println("Error caught inside output thread : "+e);
                   output.start();     
                   Thread input=new Thread()
                        public void run()
                             try
                                  //Input starts from here
                                  Reader in=new InputStreamReader(new BufferedInputStream(new CipherInputStream(theConnection.getInputStream(), desDec)),"ASCII");          
                                  System.out.println("it will not be printed");
                                  StringBuffer strbuf=new StringBuffer();
                                  int c;
                                  while (true)
                                       c=in.read();
                                       if(c=='\n' || c==-1)
                                            break;
                                       strbuf.append((char)c);     
                                  String str=strbuf.toString();
                                  System.out.println("Message from Server : "+str);
                             catch(Exception e)
                                  System.out.println("Error caught inside input Thread : "+e);
                   input.start();
                   try
                        output.join();
                        input.join();
                   catch(Exception e)
                   theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static void main(String args[])
              clientSocketDemo client=new clientSocketDemo();     
    **** I know that the CInput tries to read some header stuff thats why i used two threads for input and output.
    Waiting for the reply.
    Thank you.

    Do not ever post your code unless requested to. It is very annoying.
    Try testing what key is being used. Just to test this out, build a copy of your program and loop the input and outputs together. Have them print the data stream onto the screen or a text file. Compare the 1st Output and the 2nd Output and the 1st Input with the 2nd Input and then do a static test of the chipher with sample data (same data which was outputted), then do another cipher test with the ciphertext created by the first test.
    Everything should match - if it does not then follow the steps below.
    Case 1: IO Loops do not match
    Case 2: IO Loops match, but ciphertext 1st run does not match loop
    Case 3: IO Loops match, 1st ciphertext 1st run matches, but 2nd run does not
    Case 4: IO Loops match, both chiphertext runs do not match anything
    Case 5: Ciphertext runs do not match eachother when decrypted correctly (outside of the test program)
    Problems associated with the cases above:
    Case 1: Private Key is changing on either side (likely the sender - output channel)
    Case 2: Public Key is changing on either side (likely the sender - output channel)
    Case 3: Private Key changed on receiver - input channel
    Case 4: PKI failure, causing private key and public key mismatch only after a good combination was used
    Case 5: Same as Case 4

  • Problem with Compression (Deflater & GZip)

    Hi All,
    I've large data as a String which I need to save in Oracle in VARCHAR2 column. As Varchar2 allows maximum of 4000 characters, I wish to compress this String and save in DB.
    I tried to compress the String using Delfater and GZip. In both methods I uses Streams concep (DeflaterOutputStream, GZipOutputStream) and both Classes have the option to return the Compressed data in byte[] and String format.
    When I returned in String format, the same String is giving error while decompressing "java.util.zip.ZipException: incorrect data check". How to solve this problem.
    When I tried to save the compressed String in DB (Oracle),
    initially I got the error "java.sql.SQLException: Malformed SQL92 string at position: 1109"
    and later I tried to save like this 'strCompressed.replace("'","''") i.e., I replaced all single quotes to 2-single quotes and the error message is "java.sql.SQLException: ORA-00911: invalid character".
    Is there any character to replace in the compressed String. and how to solve the problem with decompression.
    Please help me in this.
    Thanks in advance.
    Regards
    Pavan Pinnu.

    both Classes have the option to return the Compressed data in byte[] and String format.Don't do that. String is not a container for binary data. You can't use it for compressed data. Use the byte[], send the byte[] to the database, get it back from the database, uncompress it, and then turn that back into a String.

  • GZIPOutputStream error

    All,
    THis is what I am trying to do:
    Compress a string using GZIPOutputStream and insert into a BLOB column in MySQL Database (4.0.20)
    and retrieve the BLOB value from the database and uncompress it. I get an error when I uncompress the string. If I do not compress it the program works fine.
    I am getting the following exception at line:
    "GZIPInputStream unzip = new GZIPInputStream(bios);"
    java.io.IOException: Not in GZIP format
    at java.util.zip.GZIPInputStream.readHeader(Unknown Source)
    at java.util.zip.GZIPInputStream.<init>(Unknown Source)
    at java.util.zip.GZIPInputStream.<init>(Unknown Source)
    at TestMySQLBlob.uncompress(TestMySQLBlob.java:207)
    at TestMySQLBlob.readClob(TestMySQLBlob.java:114)
    at TestMySQLBlob.main(TestMySQLBlob.java:34)
    Could somebody point out what I am doing wrong? I have the code below.
    Thanks
    import java.sql.*;
    import java.util.*;
    import java.util.zip.*;
    import java.io.*;
    public class TestMySQLBlob
    public TestMySQLBlob ()
    public static void main(String args[])
    String url="jdbc:mysql://localhost:3306/test";
    Connection con;
    String query = "SELECT * FROM blobtest";
    try {
    Class.forName("org.gjt.mm.mysql.Driver");
    catch (java.lang.ClassNotFoundException e) {
    System.err.print("ClassNotFoundException: ");
    System.err.println(e.getMessage());
    try {
    System.out.println("Trying to connect...");
    con = DriverManager.getConnection (url, "abc", "abc");
    System.out.println("connected!");
    writeBlob(con);
    readBlob(con);
    con.close();
    catch(Exception ex) {
    System.err.print("SQLException: ");
    ex.printStackTrace();
    private static void readBlob(Connection con)
    throws Exception
    String select = "SELECT ID, VALUE FROM BLOBTEST WHERE ID=1";
    PreparedStatement pstmt = con.prepareStatement(select);
    ResultSet rs = pstmt.executeQuery();
    while(rs.next())
    int id = rs.getInt(1);
    Blob b = rs.getBlob(2);
    long start = 1;
    long noRead = 0;
    long maxRead = 4096;
    long noBytes = b.length();
    long tobeRead = noBytes - noRead;
    int read = (tobeRead > maxRead) ? (int)maxRead : (int)tobeRead;
    StringBuffer buffer = new StringBuffer("");
    while(tobeRead > 0)
    byte[] blobBytes = b.getBytes(start, read);
    String str = getStringFromBytes(blobBytes);
    start += read;
    noRead += read;
    tobeRead = noBytes - noRead;
    read = (tobeRead > maxRead) ? (int)maxRead : (int)tobeRead;
    buffer.append(str);
    String uncompressed = uncompress(buffer.toString());
    PrintWriter pw = new PrintWriter(new FileWriter("write.xml"));
    pw.println(uncompressed);
    pw.flush();
    private static String getStringFromBytes(byte[] in)
    throws Exception
    return new String(in, "ISO-8859-1");
    private static void writeBlob(Connection con)
    throws Exception
    String data = readFile();
    String compressedString = compress(data);
    String insert = "INSERT INTO BLOBTEST VALUES (?, ?)";
    PreparedStatement pstmt = con.prepareStatement(insert);
    pstmt.setInt(1, 1);
    pstmt.setBytes(2, compressedString.getBytes());
    pstmt.execute();
    private static String readFile()
    throws Exception
    StringBuffer result = new StringBuffer("");
    BufferedReader br = new BufferedReader(new FileReader("read.xml"));
    String tmp = null;
    while((tmp = br.readLine()) != null)
    result.append(tmp);
    return result.toString();
    private static String compress(String data)
    throws Exception
    byte[] incomingBytes = data.getBytes();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream zip = new GZIPOutputStream(baos);
    for ( int i = 0; i < incomingBytes.length; i++)
    zip.write(incomingBytes);
    zip.close();
    byte[] compressedBytes = baos.toByteArray();
    String compressed = new String(compressedBytes, 0, compressedBytes.length, "ISO-8859-1");
    PrintWriter pw = new PrintWriter(new FileWriter("compressed.dat"));
    pw.println(compressed);
    pw.flush();
    return compressed;
    private static String uncompress(String data)
    throws Exception
    PrintWriter pw = new PrintWriter(new FileWriter("compressed_retr.dat"));
    pw.println(data);
    pw.flush();
    byte[] dataBytes = null;
    //try
    dataBytes = data.getBytes();
    //catch(java.io.UnsupportedEncodingException e)
    // System.err.println(e);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ByteArrayInputStream bios = new ByteArrayInputStream(dataBytes);
    GZIPInputStream unzip = new GZIPInputStream(bios);
    int in = unzip.read();
    while (in != -1)
    baos.write(in);
    in = unzip.read();
    unzip.close();
    return new String(baos.toByteArray());
    }

    It's probably a problem with all this toing and froing between characters and bytes, maybe where you convert data to bytes in the uncompress without specifying a character encoding. Why not work entirely in byte arrays, at least on the database side of the compression/decompression?

  • Problem when ObjectInput/OutputStream is used with GZIPStreams

    I am writing a Remort method invocation system as a part of a large project (Dont ask why I am re implementing the wheel of RMI RMI does not fit to my requirements)
    I am using ObjectStream to send method calls and receive return data I tried the use GZIPStreams to compress the data to minimize the network usage. But the problem is GZIPOutputStream does not send data to the underlaying Stream if I call flush in ObjectOutputStream which is at the top when the buffer of the GZIPStream is not full.
    So in the receive end just hangs. causing a dead lock.
    Setting the buffer to a very small size can fix the problem but it will reduce the performance so that option is out of the table
    How can I fix this problem Is their any compression streams which lets me to flush by force.

    Call finish() method of GZIPOutputStream
    But I had problem with GZIP . We cannot pass another object using the same stream after finish()

  • Compressed String (GZIPOutputStream) is not equal to the source string

    Hello,
    I would like to compress the contents of a String (XML data) with the GZIPOutput/InputStream classes. Unfortunately I'm facing a problem - my source and result strings do not equal after the compression and decompression (I hope this is the correct sub-forum for this kind of question).
    Here is a example code that reads data from a file (test.xml), compresses it via a GZIPOutputStream into compressed byte array and decompresses it back into a String:
    public class CompressedStringTest {
         private static final String     FILENAME     = "test.xml";
         public CompressedStringTest() throws IOException {
              File file = new File( FILENAME );
              String xml = FileUtil.readFile( file );
              // COMPRESS
              ByteArrayOutputStream out = new ByteArrayOutputStream();
              GZIPOutputStream zipout = new GZIPOutputStream( out );
              zipout.write( xml.getBytes() );
              zipout.close();
              out.close();
              // DECOMPRESS
              byte[] result = new byte[ xml.getBytes().length ];
              ByteArrayInputStream in = new ByteArrayInputStream( out.toByteArray() );
              GZIPInputStream zipin = new GZIPInputStream( in );
              zipin.read( result );
              zipin.close();
              in.close();
              String xml2 = new String( result );
              System.out.println( "xml.equals( xml2 ): " + xml.equals( xml2 ) );
         public static void main( String[] args ) throws IOException {
              new CompressedStringTest();
    }The length of the source and result strings are the same, but they are not equal. When I print out the lines which do not equal, I get this:
    '</sysConfig>'
    '</sxxxxxxxxx'where "x" are those small boxes, characters that can't be printed.
    This is the source XML file I use:
    <?xml version="1.0" encoding="UTF-8"?>
    <sysConfig xid="0" version="0.1" id="1" xmlns:r2="http://....">
        <addresses class="java.util.ArrayList" xid="1">
            <address xid="2" id="1">
                <config xref="0"/>
                <addressType xid="3">NURSING_SERVICE</addressType>
                <externalId xid="4">0</externalId>
                <name xid="5">This is the name containing fourtyeight chars!!!</name>
                <street xid="6">street</street>
                <city xid="7">city</city>
                <zip xid="8">zip</zip>
                <telephone xid="9">12345</telephone>
                <fax xid="10">(123) 12345612345454597745</fax>
            </address>
         </addresses>
        <lastModified class="java.util.GregorianCalendar" xid="8167">2009-09-17 10:38:59.0 MESZ</lastModified>
        <customerNr xid="8168">FB-IK-01001</customerNr>
        <customerName xid="8169">A Customer</customerName>
        <logProtocolChanges>false</logProtocolChanges>
        <useHomeAsStartAddress>false</useHomeAsStartAddress>
        <sendMailEnabled>false</sendMailEnabled>
        <sendFaxEnabled>true</sendFaxEnabled>
    </sysConfig>When I remove just one arbitrary line, the source and result strings do equal. This may have to do with some kind of buffer-length-problem, but I just can't figure out where the problem is.
    I really appreciate your help
    Thanks a lot!

    The javadoc reads for "FilterInputStream.read(byte[] b)":I've read it. You're the one who needs to read it.
    Reads up to* byte.length bytes of data from this input stream into an array of bytesSo I thought it just reads all available data.Why? That's not what it says, is it?
    But when I print the return code of "read", it is not -1, meaning not the whole data has been read.If that is supposed to be 'meaning that the whole data has been read', you are mistaken. What was the return value? compared to the buffer length? You might find it interesting ...
    I assume I just do not understand the read method completely.The return value is -1 for EOS, otherwise the number of bytes that were read. Just like it says in the Javadoc actually.
    You have to use a loop, increment the offset, etc.

  • Help-- Using GZIPOutputStream, but never end.

    I written serialization object with GZIPOutputStream.
    But recent my Aplication hang 24 hours. I print stack , see the thread is runnable,and lock (0x20fbca10)
    Can any one help me?How the "Deflater.deflateBytes" never end?
    I have two thread.
    thread 1: write serialization object (when receive a message)
    thread 2: close GZip file(when a stop request)
    "RMI TCP Connection(22352)-10.9.146.14" daemon prio=6 tid=0x0792b8d8 nid=0x7b18 runnable [0x4b01d000..0x4b01fa18]
    java.lang.Thread.State: RUNNABLE
         at java.util.zip.Deflater.deflateBytes(Native Method)
         at java.util.zip.Deflater.deflate(Deflater.java:290)
         - locked <0x20fbca10> (a java.util.zip.Deflater)
         at java.util.zip.DeflaterOutputStream.deflate(DeflaterOutputStream.java:159)
         at java.util.zip.DeflaterOutputStream.write(DeflaterOutputStream.java:118)
         at java.util.zip.GZIPOutputStream.write(GZIPOutputStream.java:72)
         - locked <0x1ff90e98> (a java.util.zip.GZIPOutputStream)
         at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
         at java.io.BufferedOutputStream.write(BufferedOutputStream.java:109)
         - locked <0x1f41f740> (a java.io.BufferedOutputStream)
         at java.io.FilterOutputStream.write(FilterOutputStream.java:80)
    "MessageListenerThread - F_LinkTopic" prio=6 tid=0x05def670 nid=0x16d8 waiting for monitor entry [0x0f90f000..0x0f90fd98]
    java.lang.Thread.State: BLOCKED (on object monitor)
         at java.util.zip.Deflater.deflate(Deflater.java:284)
         - locked <0x20fbca10> (a java.util.zip.Deflater)
         at java.util.zip.GZIPOutputStream.finish(GZIPOutputStream.java:86)
         at java.util.zip.DeflaterOutputStream.close(DeflaterOutputStream.java:146)
         at java.io.FilterOutputStream.close(FilterOutputStream.java:143)

    I have seen an almost identical problem within an Apache CXF web service. In my situation the end of the stack looks almost identical, stuck forever (apparently) inside the native Deflater.deflateBytes.
    In my situation I have seen this with two threads, each independently using GZIPOutputStream.
    I am really starting to think that there is a thread safety issue with the native GZIP code - two independent objects in two threads are simultaneously zipping and both get stuck with 100% CPU utilization in the native code. Interestingly my situation is also in the close processing, but not inside the finish processing. Of all the situations I see with searching for similar situations (search the web for Deflater.java:306) there seems to be a set of common circumstances:
    * Exactly the same last few levels on the stack (ending in Deflater.deflateBytes (Native Method)
    * Two threads interacting with GZIP
    * Often seems to relate to close processing (perhaps a short data remainder problem?)
    My situation is documented here:
    http://www.java.net/forum/topic/glassfish/glassfish/glassfish-301-gzip-problem-threads-apparently-spinning-100-cpu-use
    Salient details of thread dump:
    "http-thread-pool-8080-(18)" - Thread t@950
    java.lang.Thread.State: RUNNABLE
    at java.util.zip.Deflater.deflateBytes(Native Method)
    at java.util.zip.Deflater.deflate(Deflater.java:306)
    - locked <21b0c5> (a java.util.zip.ZStreamRef)
    at java.util.zip.DeflaterOutputStream.deflate(DeflaterOutputStream.java:159)
    at java.util.zip.DeflaterOutputStream.write(DeflaterOutputStream.java:118)
    at java.util.zip.GZIPOutputStream.write(GZIPOutputStream.java:72)
    - locked <132ba84> (a java.util.zip.GZIPOutputStream)
    at org.apache.cxf.io.AbstractWrappedOutputStream.write(AbstractWrappedOutputStream.java:46)
    at org.apache.cxf.io.AbstractThresholdOutputStream.write(AbstractThresholdOutputStream.java:69)
    at org.apache.cxf.io.AbstractWrappedOutputStream.write(AbstractWrappedOutputStream.java:46)
    at org.apache.cxf.io.AbstractThresholdOutputStream.unBuffer(AbstractThresholdOutputStream.java:89)
    at org.apache.cxf.io.AbstractThresholdOutputStream.close(AbstractThresholdOutputStream.java:100)
    at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
    at org.apache.cxf.transport.http.AbstractHTTPDestination$BackChannelConduit.close(AbstractHTTPDestination.java:619)

  • Socket + GZip Stream + Object Stream problem

    Hello,
    I've been having a problem with my threaded networked application. I want to send GZipped Objects over a socket, but the ObjectInputStream constructor blocks. I understand that it is waiting for header information from the corresponding ObjectOutputStream. I am sure that the socket connection has been established, and the ObjectOutputStream is constructed before the ObjectInputStream on the other end. The header information never seems to get to the other end.
    If I remove the Gzip filter stream, everything works great. I'm thinking that the Gzip stream is buffering the 4 bytes of header info, waiting for more data before actually compressing anything. I've tried flushing everything, to no help. I've tried finish()ing the Gzip stream, but that means I can't send my object payload. I've checked the buffers of all the stream objects and see the Object Stream's header in its buffer, but never seems to get into the GZIPOutputStream's buffer.
    Has anyone successfully used Object Stream > GZIP Stream > Socket Stream before?
    I'm not interested in examples that use file streams, since I get the impression that Gzip works fine with those (and maybe even designed only for those, not for sockets).
    Thanks for any help.
    Dave C

    Thanks. I see what I'm doing differently now. I was trying to send multiple objects over the gzip stream, not 1 at a time, finish(), and construct a new Gzip and Object output stream.
    Seems to work with a ByteArrayOutput/InputStream, now to try with a socket..

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • J2ME problem with threads

    Hi all,
    I would like to ask you for a help. I need to write a small program at my university. I started to write a midlet which function would be to countdown time for sports activities. I woul like to start a new thread - the one that counts down - and at the same time make the main thread sleep. After the "countdown" thread finishes, the main thread wakes up and waits for user input. The problem is that when the "countdown" thread finishes his work, I've got Uncaught exception java/lang/NullPointerException. error and the midlet halts.
    Below you can find the code
    import java.lang.*;
    import java.util.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class intervals extends MIDlet implements CommandListener
    public Display ekran;
    private SweepCanvas sweeper;
    private Form rundy;
    private TextField round0, round1, round2, round3, round4, round5, round6, round7, round8;
    private long czas,x;
    private Command exitCommand;
    private Command addRound;
    private Command delRound;
    private Command start;
    private TextField repeat;
    private Form odliczanie;
    private Alert ostrz;
    Licznik thread;
    String test;
    StringItem test1;
    int parz,i,j,k;
    static int l;
    int ilrund;
    int ilpowt;
    Item sec;
    long sec1;
    public intervals()
        rundy = new Form("Interwa&#322;y sportowe");
        exitCommand = new Command("Wyj&#347;cie", Command.EXIT, 2);
        addRound = new Command("Dodaj","Dodaj rund&#281;", Command.ITEM,1);
        delRound = new Command("Usu&#324;","Usu&#324; ostatni&#261; rund&#281;", Command.ITEM,1);
        start = new Command("Start", Command.ITEM,1);
        odliczanie = new Form("Odliczanie");
        TextField dodaj(TextField kolej)
            kolej=new TextField("Podaj czas (s) rundy "+parz,null, 4, TextField.NUMERIC);//stworzenie nowej instancji do wybierania czasu trwania rundy
            if(rundy.size()==0)
                rundy.insert(rundy.size(),kolej);
                else
                    rundy.insert(rundy.size()-1, kolej);
            return kolej;
        void odliczanie(TextField round)
            monitor m=new monitor();
            k=Integer.parseInt(round.getString());
            ekran.setCurrent(odliczanie);
            thread=new Licznik(k,odliczanie);
            thread.start();
            ekran.setCurrent(rundy);
    public void startApp()// throws MIDletStateChangeException
        rundy.deleteAll();
        repeat = new TextField("Podaj ilo&#347;&#263; powtórze&#324;",null,1,TextField.NUMERIC);
        rundy.addCommand(addRound);
        rundy.addCommand(exitCommand);
        rundy.setCommandListener(this);
        Canvas obrazek = new MyCanvas();
        ekran = Display.getDisplay(this);
        ekran.setCurrent(obrazek);
        czas=System.currentTimeMillis();
        while (System.currentTimeMillis()<czas+1000)
            continue;
        ekran.setCurrent(rundy);
    public void pauseApp()
    public void destroyApp(boolean unconditional)
        notifyDestroyed();
    public void commandAction(Command c, Displayable s)
        if (c == exitCommand)
            destroyApp(false);
            notifyDestroyed();
        else if(c==addRound)
            if(rundy.size()==0)//Sprawdzenie ilo&#347;ci elementów w celu poprawnego wy&#347;wietlania liczby rund w formie
                parz=1;
                else
                parz=rundy.size();
            switch(parz)
                case 1:
                    round0=dodaj(round0);break;
                case 2:
                    round1=dodaj(round1);break;
                case 3:
                   round2= dodaj(round2);break;
                case 4:
                    round3=dodaj(round3);break;
                case 5:
                    round4=dodaj(round4);break;
                default:
                    ostrz=new Alert("Uwaga","Maksymalna liczba rund wynosi 9", null, AlertType.INFO);
                    ostrz.setTimeout(3000);
                    ekran.setCurrent(ostrz);
            if(rundy.size()==1)
                rundy.append(repeat);
                rundy.addCommand(start);
            rundy.addCommand(delRound);
        else if(c==delRound)
            if(rundy.size()!=0)
                rundy.delete(rundy.size()-2);
                if (rundy.size()==1)
                    rundy.deleteAll();
                if(rundy.size()==0)
                    rundy.removeCommand(delRound);
                    rundy.removeCommand(start);
        else if(c==start)
            ilrund=rundy.size()-1;
            if(this.repeat.size()>0)
                ilpowt=Integer.parseInt(this.repeat.getString());
            ekran = Display.getDisplay(this);
            for (i=1; i<=ilpowt;i++)
                odliczanie= new Form("Odliczanie");
                 for (j=0;j<ilrund;j++)
                    switch(j)
                         case 0:
                             odliczanie(round0);
                             break;
                         case 1:
                             odliczanie(round1);
                             break;
                         case 2:
                             odliczanie(round2);
                             break;
                         case 3:
                             odliczanie(round3);
                             break;
                         case 4:
                             odliczanie(round4);
                             break;
                         case 5:
                             odliczanie(round5);
                             break;
                         case 6:
                             odliczanie(round6);
                             break;
                         case 7:
                             odliczanie(round7);
                             break;
                         case 8:
                             odliczanie(round8);
                             break;
    class Licznik extends Thread
        int czas1,k;
        Form forma;
        monitor m;
        public Licznik(int k,Form formap)
            czas1=k;
            forma=formap;
        public synchronized void run()
            while(czas1>0)
                forma.deleteAll();
                forma.append("Czas pozosta&#322;y (s): "+czas1);
                try{Thread.sleep(1000);} catch(InterruptedException e){e.printStackTrace();}
                czas1--;
            if(czas1<=0)
                m.put();
        }and monitor class
    public class monitor
    boolean busy=false;
    synchronized void get()
        if(!busy)
            try
                wait();
            }catch(InterruptedException e){e.printStackTrace();}
        notify();
    synchronized void put()
        if(busy)
            try
            wait();
            }catch(InterruptedException e){e.printStackTrace();}
        busy=true;
        notify();
    }Can anybody help me with this?

    Groovemaker,
    Your Licznik class has a member m of type monitor, which has not been instantiated (in other words is null) hence, when calling m.put() you get NullPointerException. Please also mind, that using Thread.sleep(1000) is not an accurate way of measuring time.
    If I may, please use recommended for Java class naming conventions - some of your names use lower case, while other don't which is confusing to the reader.
    Daniel

  • Problem with threads within applet

    Hello,
    I got an applet, inside this applet I have a singleton, inside this singleton I have a thread.
    this thread is running in endless loop.
    he is doing something and go to sleep on and on.
    the problem is,
    when I refresh my IE6 browser I see more than 1 thread.
    for debug matter, I did the following things:
    inside the thread, sysout every time he goes to sleep.
    sysout in the singleton constructor.
    sysout in the singleton destructor.
    the output goes like this:
    when refresh the page, the singleton constructor loading but not every refresh, sometimes I see the constructor output and sometimes I dont.
    The thread inside the singleton is giving me the same output, sometime I see more than one thread at a time and sometimes I dont.
    The destructor never works (no output there).
    I don't understand what is going on.
    someone can please shed some light?
    thanks.
    btw. I am working with JRE 1.1
    this is very old and big applet and I can't convert it to something new.

    Ooops. sorry!
    I did.
         public void start() {
         public void stop() {
         public void destroy() {
              try {
                   resetAll();
                   Configuration.closeConnection();
                   QuoteItem.closeConnection();
              } finally {
                   try {
                        super.finalize();
                   } catch (Throwable e) {
                        e.printStackTrace();
         }

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

Maybe you are looking for