BrightSide Workbench Full Report + Source Code
QueuedSender.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2021 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 package org.turro.mail.queue;
20 
21 import java.util.concurrent.locks.Lock;
22 import java.util.concurrent.locks.ReentrantLock;
23 import java.util.logging.Level;
24 import java.util.logging.Logger;
25 import org.turro.elephant.context.ElephantContext;
26 import org.turro.util.AtomicCounter;
27 
32 public abstract class QueuedSender implements Runnable {
33 
34  public QueuedSender() {
35  }
36 
37  protected abstract void doSend();
38 
39  public void send() {
40  Thread sender = new Thread(this, "QueuedSenderTask");
41  sender.start();
42  }
43 
44  public void pause() {
45  try {
46  Thread.sleep(300);
47  } catch (InterruptedException ex) {
48  Logger.getLogger(QueuedSender.class.getName()).log(Level.SEVERE, ElephantContext.logMsg("Pausing..."), ex);
49  }
50  }
51 
52  /* Runnable */
53 
54  @Override
55  public void run() {
56  SENDER_LOCK.lock();
57  try {
58  openSenders.increment();
59  try{
60  doSend();
61  } catch(Exception ex) {
62  Logger.getLogger(QueuedSender.class.getName()).log(Level.SEVERE, ElephantContext.logMsg("Sending..."), ex);
63  }
64  } finally {
65  openSenders.decrement();
66  SENDER_LOCK.unlock();
67  }
68  }
69 
70  /* Lock for senders */
71 
72  private static final Lock SENDER_LOCK = new ReentrantLock();
73 
74  /* Debug */
75 
76  private static final AtomicCounter openSenders = new AtomicCounter();
77 
78  public static AtomicCounter getCounter() {
79  return openSenders;
80  }
81 
82 }
static AtomicCounter getCounter()