I used to implement the Runnable
interface to peek()
an item from a queue and send it to an API.
But now I need to use Callable
interface to peek()
the queue and send an item to an API. If return 200, then delete the item from the queue.
Here is the code I used to implement this functionality. How can I modify the code? Any examples or reference about this? Thanks.
public class QueueProcessor implements Runnable{
private static ObjectQueue<JSONObject> objectQueue;
static {
objectQueue = new ObjectQueue<JSONObject>();
}
public void run() {
//add items to the queue
objectQueue.add(jsonObeject)
Random r = new Random();
try {
while (true) {
try {
if (!objectQueue.isEmpty()) {
JSONObject o = objectQueue.remove();
sendRequest(o.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP));
}
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
public void sendRequest(JSONObject json) {
Client client = ClientBuilder.newClient();
WebTarget baseTarget = client.target("someUrl");
Invocation.Builder builder = baseTarget.request();
Response response = builder.post(Entity.entity(json.toString(), MediaType.APPLICATION_JSON));
int code = response.getStatus();
if (200 == code) {
objectQueue.remove();
}
}