I can't see any issues with your code, it's exactly what I would do. What MQTT Broker are you using? I tested the following against mosquitto which worked fine:
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class AuthTest {
public static void main( String[] args )
{
String topic = "auth_test";
String content = "Message from MqttPublishSample";
int qos = 0;
String broker = "tcp://localhost";
String clientId = "auth_test";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttAsyncClient sampleClient = new MqttAsyncClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setMaxInflight(1000);
connOpts.setUserName("USERNAME");
connOpts.setPassword("PASSWORD".toCharArray());
System.out.println("Connecting to broker: "+broker);
IMqttToken conToken = sampleClient.connect(connOpts);
conToken.waitForCompletion();
System.out.println("Connected");
System.out.println("Publishing message: "+content);
System.out.println("About to send messages");
for(int i = 0; i < 10; i++){
sampleClient.publish(topic, new MqttMessage(content.getBytes()));
}
sampleClient.disconnect();
System.out.println("Disconnected");
System.exit(0);
} catch(MqttException me) {
System.out.println("reason "+me.getReasonCode());
System.out.println("msg "+me.getMessage());
System.out.println("loc "+me.getLocalizedMessage());
System.out.println("cause "+me.getCause());
System.out.println("excep "+me);
me.printStackTrace();
}
}
}