I understand the difference between print and println methods.
But why Gradle with default logging level prints output with println but doesn't with print or printf?
TaskProgress.groovy
public class TaskProgress {
private static final String PROGRESS_SYMBOLS = '_/\\_';
private static final int MAX_POINTS = PROGRESS_SYMBOLS.length() - 2
AtomicBoolean inProgress = new AtomicBoolean(true)
int currentChar = 0
int delta = 1
private TaskProgress() {}
static TaskProgress doProgress() {
Log.error("START PROGRESS")
def taskProgress = new TaskProgress();
taskProgress.startProgress()
return taskProgress
}
private void startProgress() {
Thread.start {
Log.error('STARTING:')
while (inProgress.get()) {
if (currentChar > MAX_POINTS) {
delta = -1
} else if (currentChar == 0) {
delta = 1
}
println PROGRESS_SYMBOLS[currentChar] // it works
print PROGRESS_SYMBOLS[currentChar] // it doesn't work
currentChar += delta
if (!inProgress.get()) break;
}
Log.error('STOPPING:')
}
}
public void stopProgress() {
Log.error("STOP PROGRESS")
inProgress.set(false)
}
}
buid.gradle
task progress {
doLast {
def progress = TaskProgress.doProgress()
Thread.sleep(1000)
progress.stopProgress()
}
}
When I use print in the main thread it works okay. Is it a defect?
I raised a topic on official gradle forum: Gradle print vs println
Related
What's the most performant way in Kotlin to allow concurrent file I/O in multi-reader, single-writer fashion?
I have the below, but I'm unsure how much overhead is being created by the coroutine facilities:
AsyncFileChannel, with extension functions to use it in a suspend context
Taken from example here: https://github.com/Kotlin/coroutines-examples/blob/master/examples/io/io.kt
DiskManager class, that uses a custom ReadWriteMutex
Searching for examples of this doesn't turn up much (try searching Github for ReadWriteMutex, there are a tiny handful of Kotlin repos implementing this).
class DiskManagerImpl(file: File) : DiskManager {
private val mutex = ReadWriteMutexImpl()
private val channel = AsynchronousFileChannel.open(file.toPath(),
StandardOpenOption.READ, StandardOpenOption.WRITE)
override suspend fun readPage(pageId: PageId, buffer: MemorySegment) = withContext(Dispatchers.IO) {
mutex.withReadLock {
val offset = pageId * PAGE_SIZE
val bytesRead = channel.readAsync(buffer.asByteBuffer(), offset.toLong())
require(bytesRead == PAGE_SIZE) { "Failed to read page $pageId" }
}
}
override suspend fun writePage(pageId: PageId, buffer: MemorySegment) = withContext(Dispatchers.IO) {
mutex.withWriteLock {
val offset = pageId * PAGE_SIZE
val bytesWritten = channel.writeAsync(buffer.asByteBuffer(), offset.toLong())
require(bytesWritten == PAGE_SIZE) { "Failed to write page $pageId" }
}
}
}
class ReadWriteMutexImpl : ReadWriteMutex {
private val read = Mutex()
private val write = Mutex()
private val readers = atomic(0)
override suspend fun lockRead() {
if (readers.getAndIncrement() == 0) {
read.lock()
}
}
override fun unlockRead() {
if (readers.decrementAndGet() == 0) {
read.unlock()
}
}
override suspend fun lockWrite() {
read.lock()
write.lock()
}
override fun unlockWrite() {
write.unlock()
read.unlock()
}
}
suspend inline fun <T> ReadWriteMutex.withReadLock(block: () -> T): T {
lockRead()
return try {
block()
} finally {
unlockRead()
}
}
suspend inline fun <T> ReadWriteMutex.withWriteLock(block: () -> T): T {
lockWrite()
return try {
block()
} finally {
unlockWrite()
}
}
I am trying to create a program that collects the score at the end and assigns it a grade but it is assigning the grade for every score printed. In layman's terms the system should go through each method and deduct points based on whether the condition is met. Its for a website so I would need to display the scores so I need to use an entity class with getters and setters from what I have read. I am quite lost about how to go about this
public class Review {
public static void main(String[] args) { //getWordLength() { // Checking word length. Less than 6 means reviewer can't weigh out positives and negatives
// TODO Auto-generated method stub
int ReviewScore = 30;
String Review = "me I me, pizza Montreal";
String[] words = Review.split("\\s+");
System.out.println("Word Count is: "+words.length);
int wordlength = Integer.valueOf(words.length);
if (wordlength< 6) {
ReviewScore -=4; // deducts 4pts if review less than 6 words
System.out.println("Score is "+ ReviewScore);
}
verbCount( ReviewScore,Review );
}
public static void verbCount (int ReviewScore, String Review) { //Count verbs 'I' or 'me'
for (String s : Review.split ("\\s+") ) { // splits review into separate words
if (s.contains("me" )){ // Checks for 'me' or 'I'
ReviewScore -= 1;
System.out.println("Score is "+ ReviewScore);
// deducts by 2 pts for each time 'I' is mentioned
}
if ( s.contains ("I")) {
ReviewScore -= 1;
System.out.println("Score is "+ ReviewScore); //deducts by 2 pts for each time 'me' is mentioned
}
WordBucket (ReviewScore, s);
}
}
public static void WordBucket ( int ReviewScore, String s) {
for (String word : Analyser.FREQWORDS) {
if(s.contains(word)) {
System.out.println("Score is "+ ReviewScore);
break;
}
else {
ReviewScore -=5;
System.out.println("Score is "+ ReviewScore);
break;
}
}
Grade (ReviewScore) ;
}
public static void Grade (int ReviewScore) {
int Finalscore= ReviewScore;
if (Finalscore >=20 && Finalscore <=25) {
System.out.println ("a");
} else if (Finalscore >=14 && Finalscore <=19) {
System.out.println ("b");
} else if (Finalscore >=7 && Finalscore <=13 ) {
System.out.println ("c");
} else if ( Finalscore <6)
System.out.println ("d");
else {
System.out.println ("an error has occured") ;
}
}
}
I Believe this is the solution for your query. I understand that you want to print/pass the final Score as well as grade to entity class so in this way we can do where
a) instead of passing each and every word to subsequent function, you are passing the String array itself.
b) returning the score value from each functional call so that the corresponding scores can be saved and passed to other function call.
Also try to avoid using system Print out since it is just for printing to console purpose. You need to return the value from each and every call. If you run this program , the output you are going to get is below
Word Count is: 5
Final Score is 18
Final Grade is b
the lines below
int finalScore = verbCount(ReviewScore, words);
String finalGrade = Grade(finalScore);
Can help you pass the finalScore and finalGrade to entity class which needs to consume these values.
Please note I am using the String array ArrayAnlyser here which I believe you are using as an enum as a part of your program.
public class Review {
public static void main(String[] args) {
int ReviewScore = 30;
String Review = "me I me, pizza Montreal";
String[] words = Review.split("\\s+");
System.out.println("Word Count is: " + words.length);
int wordlength = Integer.valueOf(words.length);
if (wordlength < 6) {
ReviewScore -= 4;
}
int finalScore = verbCount(ReviewScore, words);
System.out.println("Final Score is " + finalScore);
String finalGrade = Grade(finalScore);
System.out.println("Final Grade is " + finalGrade);
}
public static int verbCount(int ReviewScore, String[] words) { //Count verbs 'I' or 'me'
for (String s : words) { // splits review into separate words
if (s.contains("me")) { // Checks for 'me' or 'I'
ReviewScore -= 1;
// System.out.println("Score is "+ ReviewScore);
// deducts by 2 pts for each time 'I' is mentioned
}
if (s.contains("I")) {
ReviewScore -= 1;
// System.out.println("Score is "+ ReviewScore); //deducts by 2 pts for each time 'me' is mentioned
}
}
int RevisedScore = WordBucket(ReviewScore, words);
return RevisedScore;
}
public static int WordBucket(int ReviewScore, String[] words) {
String[] ArrayAnlyser = {"me", "I", "pizza", "Montreal"};
boolean flag = false;
for (String word : words) {
flag = false;
for (String analyWord : ArrayAnlyser) {
if (analyWord.contains(word)) {
// System.out.println("Score is "+ ReviewScore);
flag = true;
break;
}
}
if (!flag) {
ReviewScore -= 5;
// System.out.println("Score is "+ ReviewScore);
}
}
return ReviewScore;
// Grade (ReviewScore) ;
}
public static String Grade(int ReviewScore) {
int Finalscore = ReviewScore;
String grade = "";
if (Finalscore >= 20 && Finalscore <= 25) {
// System.out.println ("a");
grade = "a";
} else if (Finalscore >= 14 && Finalscore <= 19) {
grade = "b";
// System.out.println ("b");
} else if (Finalscore >= 7 && Finalscore <= 13) {
grade = "c";
// System.out.println ("c");
} else if (Finalscore < 6) {
grade = "d";
// System.out.println ("d");
} else {
grade = "error occured";
// System.out.println ("an error has occured") ;
}
return grade;
}
}
Trying to work on small use case where i have to add string of websites in a queue. if the site repeats then i have to update the numberofVisits+1. Else i would add that object into the queue. Something wrong with updateCount code. Please let me know
here is the code snippet. I am unable to move forward on this.
public CLassName(String url, int numVisits) {
this.url = url;
this.numVisits = numVisits;
}
public int getNumVisits() {
return this.numVisits;
}
public String getUrl() {
return this.url;
}
public void setNumVisits(int updatedNumVisits) {
this.numVisits = updatedNumVisits;
}
private static Queue<ClassName> sites = new LinkedList<ClassName>();
// Method to find the website in the queue and increment the visited count by 1, adding new node in case website is not found
public static void update(String url) {
//code should go in here. // THis is wrong code
if (sites.isEmpty()) sites.add(new ClassName(url,1));
while(!sites.isEmpty()) {
String tmpUrl = sites.peek().getUrl();
int numVisits = sites.peek().getNumVisits();
if(tmpUrl!=null && tmpUrl.equalsIgnoreCase(url)) {
sites.add(new ClassName(tmpUrl,numVisits+1));
} else if(tmpUrl!=null){
sites.add(new ClassName(tmpUrl,numVisits));
} else {
sites.add(new ClassName(url,1));
}
}
}
public static void main(String[] args) {
String[] visitedSites = { "www.google.co.in", "www.google.co.in", "www.facebook.com", "www.upgrad.com", "www.google.co.in", "www.youtube.com",
"www.facebook.com", "www.facebook.com", "www.google.co.in", "www.microsoft.com", "www.9gag.com", "www.netflix.com",
"www.netflix.com", "www.9gag.com", "www.microsoft.com", "www.amazon.com", "www.amazon.com", "www.uber.com", "www.amazon.com",
"www.microsoft.com" };
for (String url : visitedSites) {
update(url);
}
Thanks for the recommendation. I did a small tweek to address the problem.
I did not add Dummy site
Added a counter and incremented so that it is always < the size of queue
Here is my solution and it works
public static void update(Queue<String> sites,String url,int numberOfVisits)
{
if ( sites.isEmpty()) sites.add(url); // first time
boolean flag = false;
int counter = 0
while (!sites.empty && counter<sites.size()) //go over all the urls in the queue
{
if (sites.head().equalsIgnoreCase(url))
{
flag = true;
break;
}
sites.insert(sites.remove()); //removing the head and inserting it to the end of the queue
counter ++;
}
if (!flag==true) {
numberOfVisits=numberOfVisits+1;
}
else {
sites.insert(url);
}
}
the update method just could be like this;
boolean increased = false;
Iterator<ClassName> statIterator = sites.iterator();
while (statIterator.hasNext()) {
ClassName st = statIterator.next();
if (st.getUrl().equals(url)) {
st.setNumVisits(st.getNumVisits()+1);
increased = true;
break;
}
}
if (!increased) {
sites.add(new ClassName(url,1));
}
I am trying to implement below java code in c# referring to Android documentation
List<String> skuList = new ArrayList<> ();
skuList.add("premium_upgrade");
skuList.add("gas");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(SkuType.INAPP);
billingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult,
List<SkuDetails> skuDetailsList) {
// Process the result.
}
});
I have here 2 questions. I thought that i would run this code on a separate thread than UI thread like below to keep my ui responsive while network connection is done. is that the correct approach? QuerySkuDetailsAsync is called async but doesnt implement as async. how should this be working and how to handle in c# because it will fire and forget but Listener to handle the response.
public async Task<List<InAppBillingProduct>> GetProductsAsync(List<string> ProductIds)
{
var getSkuDetailsTask = Task.Factory.StartNew(() =>
{
var prms = SkuDetailsParams.NewBuilder();
var type = BillingClient.SkuType.Inapp;
prms.SetSkusList(ProductIds).SetType(type);
BillingClient.QuerySkuDetailsAsync(prms.Build(), new SkuDetailsResponseListener());
return InAppBillingProducts;
});
return await getSkuDetailsTask;
}
2nd question regarding how to handle with the listener as below. How do I return value from the listener. I need return list of InAppBillingProduct object.
public class SkuDetailsResponseListener : Java.Lang.Object, ISkuDetailsResponseListener
{
public void OnSkuDetailsResponse(BillingResult billingResult, IList<SkuDetails> skus)
{
if (billingResult.ResponseCode == BillingResponseCode.Ok)
{
// get list of Products here and return
}
}
}
FYI. This is how I did it. This is not a complete code but this will give you and idea.
Listener - PCL
============
private async Task EventClicked()
{
var skuList = new List<string>();
skuList.Add("[nameofsubscriptionfoundinyourgoogleplay]");
if (await _billingClientLifecycle.Initialize(skuList, DisconnectedConnection))
{
var firstProduct = _billingClientLifecycle?.ProductsInStore?.FirstOrDefault();
if (firstProduct != null)
{
//purchase here
}
}
}
private void DisconnectedConnection()
{
//Todo.alfon. handle disconnection here...
}
Interface - PCL
===========
public interface IInAppBillingMigratedNew
{
List<InAppBillingPurchase> PurchasedProducts { get; set; }
List<InAppBillingProduct> ProductsInStore { get; set; }
Task<bool> Initialize(List<String> skuList, Action onDisconnected = null);
}
Dependency - Platform Droid
===============
[assembly: XF.Dependency(typeof(InAppBillingMigratedNew))]
public class InAppBillingMigratedNew : Java.Lang.Object, IBillingClientStateListener
, ISkuDetailsResponseListener, IInAppBillingMigratedNew
{
private Activity Context => CrossCurrentActivity.Current.Activity
?? throw new NullReferenceException("Current Context/Activity is null");
private BillingClient _billingClient;
private List<string> _skuList = new List<string>();
private TaskCompletionSource<bool> _tcsInitialized;
private Action _disconnectedAction;
private Dictionary<string, SkuDetails> _skusWithSkuDetails = new Dictionary<string, SkuDetails>();
public List<InAppBillingPurchase> PurchasedProducts { get; set; }
public List<InAppBillingProduct> ProductsInStore { get; set; }
public IntPtr Handle => throw new NotImplementedException();
public Task<bool> Initialize(List<string> skuList, Action disconnectedAction = null)
{
_disconnectedAction = disconnectedAction;
_tcsInitialized = new TaskCompletionSource<bool>();
var taskInit = _tcsInitialized.Task;
_skuList = skuList;
_billingClient = BillingClient.NewBuilder(Context)
.SetListener(this)
.EnablePendingPurchases()
.Build();
if (!_billingClient.IsReady)
{
_billingClient.StartConnection(this);
}
return taskInit;
}
#region IBillingClientStateListener
public void OnBillingServiceDisconnected()
{
Console.WriteLine($"Connection disconnected.");
_tcsInitialized?.TrySetResult(false);
_disconnectedAction?.Invoke();
}
public void OnBillingSetupFinished(BillingResult billingResult)
{
var responseCode = billingResult.ResponseCode;
var debugMessage = billingResult.DebugMessage;
if (responseCode == BillingResponseCode.Ok)
{
QuerySkuDetails();
QueryPurchases();
_tcsInitialized?.TrySetResult(true);
}
else
{
Console.WriteLine($"Failed connection {debugMessage}");
_tcsInitialized?.TrySetResult(false);
}
}
#endregion
#region ISkuDetailsResponseListener
public void OnSkuDetailsResponse(BillingResult billingResult, IList<SkuDetails> skuDetailsList)
{
if (billingResult == null)
{
Console.WriteLine("onSkuDetailsResponse: null BillingResult");
return;
}
var responseCode = billingResult.ResponseCode;
var debugMessage = billingResult.DebugMessage;
switch (responseCode)
{
case BillingResponseCode.Ok:
if (skuDetailsList == null)
{
_skusWithSkuDetails.Clear();
}
else
{
if (skuDetailsList.Count > 0)
{
ProductsInStore = new List<InAppBillingProduct>();
}
foreach (var skuDetails in skuDetailsList)
{
_skusWithSkuDetails.Add(skuDetails.Sku, skuDetails);
//ToDo.alfon. make use mapper here
ProductsInStore.Add(new InAppBillingProduct
{
Name = skuDetails.Title,
Description = skuDetails.Description,
ProductId = skuDetails.Sku,
CurrencyCode = skuDetails.PriceCurrencyCode,
LocalizedIntroductoryPrice = skuDetails.IntroductoryPrice,
LocalizedPrice = skuDetails.Price,
MicrosIntroductoryPrice = skuDetails.IntroductoryPriceAmountMicros,
MicrosPrice = skuDetails.PriceAmountMicros
});
}
}
break;
case BillingResponseCode.ServiceDisconnected:
case BillingResponseCode.ServiceUnavailable:
case BillingResponseCode.BillingUnavailable:
case BillingResponseCode.ItemUnavailable:
case BillingResponseCode.DeveloperError:
case BillingResponseCode.Error:
Console.WriteLine("onSkuDetailsResponse: " + responseCode + " " + debugMessage);
break;
case BillingResponseCode.UserCancelled:
Console.WriteLine("onSkuDetailsResponse: " + responseCode + " " + debugMessage);
break;
// These response codes are not expected.
case BillingResponseCode.FeatureNotSupported:
case BillingResponseCode.ItemAlreadyOwned:
case BillingResponseCode.ItemNotOwned:
default:
Console.WriteLine("onSkuDetailsResponse: " + responseCode + " " + debugMessage);
break;
}
}
#endregion
#region Helper Methods Private
private void ProcessPurchases(List<Purchase> purchasesList)
{
if (purchasesList == null)
{
Console.WriteLine("No purchases done.");
return;
}
if (IsUnchangedPurchaseList(purchasesList))
{
Console.WriteLine("Purchases has not changed.");
return;
}
_purchases.AddRange(purchasesList);
PurchasedProducts = _purchases.Select(sku => new InAppBillingPurchase
{
PurchaseToken = sku.PurchaseToken
})?.ToList();
if (purchasesList != null)
{
LogAcknowledgementStatus(purchasesList);
}
}
private bool IsUnchangedPurchaseList(List<Purchase> purchasesList)
{
// TODO: Optimize to avoid updates with identical data.
return false;
}
private void LogAcknowledgementStatus(List<Purchase> purchasesList)
{
int ack_yes = 0;
int ack_no = 0;
foreach (var purchase in purchasesList)
{
if (purchase.IsAcknowledged)
{
ack_yes++;
}
else
{
ack_no++;
}
}
//Log.d(TAG, "logAcknowledgementStatus: acknowledged=" + ack_yes +
// " unacknowledged=" + ack_no);
}
private void QuerySkuDetails()
{
var parameters = SkuDetailsParams
.NewBuilder()
.SetType(BillingClient.SkuType.Subs)
.SetSkusList(_skuList)
.Build();
_billingClient.QuerySkuDetailsAsync(parameters, this);
}
private void QueryPurchases()
{
if (!_billingClient.IsReady)
{
Console.WriteLine("queryPurchases: BillingClient is not ready");
}
var result = _billingClient.QueryPurchases(BillingClient.SkuType.Subs);
ProcessPurchases(result?.PurchasesList?.ToList());
}
#endregion
}
I have two applications, sending messages asynchronously in both directions. I am using sockets of type ZMQ.DEALER on both sides. The connection status is additionally controlled by heartbeating.
I have now problems to get the connection reliably recovering after connection problems (line failure or application restart on one side). When I restart the applicaton on the server side (the side doing the bind()), the client side will not always reconnect successfully and then needs to be restarted, especially when the local buffer has reached the HWM limit.
I did not find any other way to make the connection recovery reliable, other than resetting the complete ZMQ.Context in case of heartbeat failures or if send() returned false. I will then call Context.term() and will create Context and Socket again. This seemed to work fine in my tests. But now I observed occasional and hangups inside Context.term(), which are rare and hard to reproduce. I know, that creating the Context should be done just once at application startup, but as said I found no other way to re-establish a broken connection.
I am using JeroMQ 0.3.4. The source of a test application is below, ~200 lines of code.
Any hints to solve this are very much appreciated.
import java.util.Calendar;
import org.zeromq.ZMQ;
public class JeroMQTest {
public interface IMsgListener {
public void newMsg(byte[] message);
}
final static int delay = 100;
final static boolean doResetContext = true;
static JeroMQTest jeroMQTest;
static boolean isServer;
private ZMQ.Context zContext;
private ZMQ.Socket zSocket;
private String address = "tcp://localhost:9889";
private long lastHeartbeatReceived = 0;
private long lastHeartbeatReplyReceived;
private boolean sendStat = true, serverIsActive = false, receiverInterrupted = false;
private Thread receiverThread;
private IMsgListener msgListener;
public static void main(String[] args) {
isServer = args.length > 0 && args[0].equals("true");
if (isServer) {
new JeroMQTest().runServer();
}
else {
new JeroMQTest().runClient();
}
}
public void runServer() {
msgListener = new IMsgListener() {
public void newMsg(byte[] message) {
String msgReceived = new String(message);
if (msgReceived.startsWith("HEARTBEAT")) {
String msgSent = "HEARTBEAT_REP " + msgReceived.substring(10);
sendStat = zSocket.send(msgSent.getBytes());
System.out.println("heartbeat rcvd, reply sent, status:" + sendStat);
lastHeartbeatReceived = getNow();
} else {
System.out.println("msg received:" + msgReceived);
}
}
};
createJmq();
sleep(1000);
int ct = 1;
while (true) {
boolean heartbeatsOk = lastHeartbeatReceived > getNow() - delay * 4;
if (heartbeatsOk) {
serverIsActive = true;
String msg = "SERVER " + ct;
sendStat = zSocket.send(msg.getBytes());
System.out.println("msg sent:" + msg + ", status:" + sendStat);
ct++;
}
if (serverIsActive && (!heartbeatsOk || !sendStat)) {
serverIsActive = false;
if (doResetContext) {
resetContext();
}
}
sleep(delay);
}
}
public void runClient() {
msgListener = new IMsgListener() {
public void newMsg(byte[] message) {
String msgReceived = new String(message);
if (msgReceived.startsWith("HEARTBEAT_REP")) {
System.out.println("HEARTBEAT_REP received:" + msgReceived);
lastHeartbeatReplyReceived = getNow();
}
else {
System.out.println("msg received:" + msgReceived);
}
}
};
createJmq();
sleep(1000);
int ct = 1;
boolean reconnectDone = false;
while (true) {
boolean heartbeatsOK = lastHeartbeatReplyReceived > getNow() - delay * 4;
String msg = "HEARTBEAT " + (ct++);
sendStat = zSocket.send(msg.getBytes());
System.out.println("heartbeat sent:" + msg + ", status:" + sendStat);
sleep(delay / 2);
if (sendStat) {
msg = "MSG " + ct;
sendStat = zSocket.send(msg.getBytes());
System.out.println("msg sent:" + msg + ", status:" + sendStat);
reconnectDone = false;
}
if ((!heartbeatsOK && lastHeartbeatReplyReceived > 0) || (!sendStat && !reconnectDone)) {
if (doResetContext) {
resetContext();
}
lastHeartbeatReplyReceived = 0;
reconnectDone = true;
}
sleep(delay / 2);
}
}
public void resetContext() {
closeJmq();
sleep(1000);
createJmq();
System.out.println("resetContext done");
}
private void createJmq() {
zContext = ZMQ.context(1);
zSocket = zContext.socket(ZMQ.DEALER);
zSocket.setSendTimeOut(100);
zSocket.setReceiveTimeOut(100);
zSocket.setSndHWM(10);
zSocket.setRcvHWM(10);
zSocket.setLinger(100);
if (isServer) {
zSocket.bind(address);
} else {
zSocket.connect(address);
}
receiverThread = new Thread() {
public void run() {
receiverInterrupted = false;
try {
ZMQ.Poller poller = new ZMQ.Poller(1);
poller.register(zSocket, ZMQ.Poller.POLLIN);
while (!receiverInterrupted) {
if (poller.poll(100) > 0) {
byte byteArr[] = zSocket.recv(0);
msgListener.newMsg(byteArr);
}
}
poller.unregister(zSocket);
} catch (Throwable e) {
System.out.println("Exception in ReceiverThread.run:" + e.getMessage());
}
}
};
receiverThread.start();
}
public void closeJmq() {
receiverInterrupted = true;
sleep(100);
zSocket.close();
zContext.term();
}
long getNow() {
Calendar now = Calendar.getInstance();
return (long) (now.getTime().getTime());
}
private static void sleep(int mSleep) {
try {
Thread.sleep(mSleep);
} catch (InterruptedException e) {
}
}
}