ListeningExecutorServices+CountDownLatch+Semaphore付Fping
21306 ワード
ListeningExecutorService
CountDownLatch
Semaphore
private static ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5));
private static ListeningExecutorService resultPool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5));
private static Semaphore available = null;
private Set<String> exec(Set<String> ips) throws InterruptedException {
available = new Semaphore(20, true);
CountDownLatch latch = new CountDownLatch(ips.size());
Set<String> result = new HashSet<>();
for (String ip : ips) {
available.acquire();
ListenableFuture<String> submit = listeningExecutorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
String line = null;
Runtime runtime = Runtime.getRuntime();
try {
Process process = null;
process = runtime.exec("fping -t 100 -a " + ip);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
line = br.readLine();
is.close();
isr.close();
br.close();
} catch (Exception e) {
throw e;
}
return line;
}
});
FutureCallback<String> futureCallback = new FutureCallback<String>() {
@Override
public void onSuccess(String ip) {
available.release();
latch.countDown();
if(null!=ip){
result.add(ip);
}
}
@Override
public void onFailure(Throwable t) {
available.release();
latch.countDown();
}
};
Futures.addCallback(submit, futureCallback, resultPool);
}
latch.await();
return result;
}
完全なfping
// fping -t 100 -a -g 100.28.218.3 100.28.218.255
// fping -t 100 -u -g 100.28.218.3 100.28.218.255
// fping -t 100 100.28.218.3 100.28.218.255
//-a : (alive)
//-g : (group)
//-u : (unreacheable)。 -a
connectIpList("100.26.72.1","100.26.72.1.250");
public static Set<String> connectIpList( String start, String end, Set<String> ips) {
Set<String> connect = new HashSet<>();
Runtime runtime = Runtime.getRuntime();
Process process = null;
try {
process = runtime.exec("fping -g -a -t 100 " + start + " " + end);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
connect.add(line);
}
InputStream er = process.getErrorStream();
InputStreamReader err = new InputStreamReader(er, "GBK");
BufferedReader ebr = new BufferedReader(err);
String eine = null;
StringBuffer esb = new StringBuffer();
while ((eine = ebr.readLine()) != null) {
esb.append(eine);
}
if (esb.length() > 5) {
logger.error(" ip fping >>" + esb.toString());
}
is.close();
isr.close();
br.close();
} catch (IOException e) {
logger.error(" ip fping >>" + e);
}
return connect;
}